2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END============================================
20 * Modifications copyright (c) 2018 Nokia
21 * ===================================================================
24 package org.onap.clamp.clds.client.req.policy;
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
29 import java.io.UnsupportedEncodingException;
30 import java.net.URLEncoder;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
37 import javax.ws.rs.BadRequestException;
39 import org.onap.clamp.clds.model.properties.Global;
40 import org.onap.clamp.clds.model.properties.ModelProperties;
41 import org.onap.clamp.clds.model.properties.PolicyChain;
42 import org.onap.clamp.clds.model.properties.PolicyItem;
43 import org.onap.policy.controlloop.policy.Policy;
44 import org.onap.policy.controlloop.policy.PolicyResult;
45 import org.onap.policy.controlloop.policy.Target;
46 import org.onap.policy.controlloop.policy.TargetType;
47 import org.onap.policy.controlloop.policy.builder.BuilderException;
48 import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder;
49 import org.onap.policy.controlloop.policy.builder.Message;
50 import org.onap.policy.controlloop.policy.builder.Results;
51 import org.onap.policy.sdc.Resource;
52 import org.onap.policy.sdc.ResourceType;
53 import org.onap.policy.sdc.Service;
55 public class OperationalPolicyYamlFormatter {
56 private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicyYamlFormatter.class);
58 protected OperationalPolicyYamlFormatter() {
61 * Format Operational OpenLoop Policy yaml.
64 * @param modelElementId
67 * @throws BuilderException
68 * @throws UnsupportedEncodingException
70 public static String formatOpenLoopYaml(ModelProperties prop, String modelElementId,
71 PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException {
72 // get property objects
73 Global global = prop.getGlobal();
74 prop.setCurrentModelElementId(modelElementId);
75 prop.setPolicyUniqueId(policyChain.getPolicyId());
76 // convert values to SDC objects
77 Service service = new Service(global.getService());
78 Resource[] vfResources = convertToResources(global.getResourceVf(), ResourceType.VF);
80 ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
81 policyChain.getTimeout(), service, vfResources);
82 // builder.setTriggerPolicy(refProp.getStringValue("op.openloop.policy"));
83 // Build the specification
84 Results results = builder.buildSpecification();
86 return URLEncoder.encode(results.getSpecification(), "UTF-8");
89 public static String formatYaml(ModelProperties prop, String modelElementId,
90 PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException {
91 // get property objects
92 Global global = prop.getGlobal();
93 prop.setCurrentModelElementId(modelElementId);
94 prop.setPolicyUniqueId(policyChain.getPolicyId());
95 // convert values to SDC objects
96 Service service = new Service(global.getService());
97 Resource[] vfResources = convertToResources(global.getResourceVf(), ResourceType.VF);
98 Resource[] vfcResources = convertToResources(global.getResourceVfc(), ResourceType.VFC);
100 ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
101 policyChain.getTimeout(), service, vfResources);
102 builder.addResource(vfcResources);
103 // process each policy
104 Map<String, Policy> policyObjMap = new HashMap<>();
105 List<PolicyItem> policyItemList = orderParentFirst(policyChain.getPolicyItems());
106 for (PolicyItem policyItem : policyItemList) {
107 String policyName = policyItem.getRecipe() + " Policy";
108 Target target = new Target();
109 target.setType(TargetType.VM);
110 // We can send target type as VM/VNF for most of recipes
111 if (policyItem.getRecipeLevel() != null && !policyItem.getRecipeLevel().isEmpty()) {
112 target.setType(TargetType.valueOf(policyItem.getRecipeLevel()));
114 target.setResourceID(policyItem.getTargetResourceId());
115 String actor = policyItem.getActor();
116 Map<String, String> payloadMap = policyItem.getRecipePayload();
118 if (policyItemList.indexOf(policyItem) == 0) {
119 String policyDescription = policyItem.getRecipe()
120 + " Policy - the trigger (no parent) policy - created by CLDS";
121 policyObj = builder.setTriggerPolicy(policyName, policyDescription, actor, target,
122 policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit());
124 Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy());
125 String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by "
126 + parentPolicyObj.getName() + " - created by CLDS";
127 policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, actor, target,
128 policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(),
129 parentPolicyObj.getId(), convertToPolicyResults(policyItem.getParentPolicyConditions()));
130 logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId());
132 policyObjMap.put(policyItem.getId(), policyObj);
134 // Build the specification
135 Results results = builder.buildSpecification();
137 return URLEncoder.encode(results.getSpecification(), "UTF-8");
140 protected static List<PolicyItem> orderParentFirst(List<PolicyItem> inOrigList) {
141 List<PolicyItem> inList = new ArrayList<>();
142 inList.addAll(inOrigList);
143 List<PolicyItem> outList = new ArrayList<>();
145 while (!inList.isEmpty()) {
146 // check if there's a loop in the policy chain (the inList should
147 // have been reduced by at least one)
148 if (inList.size() == prevSize) {
149 throw new BadRequestException("Operation Policy validation problem: loop in Operation Policy chain");
151 prevSize = inList.size();
152 // the following loop should remove at least one PolicyItem from the
154 Iterator<PolicyItem> inListItr = inList.iterator();
155 while (inListItr.hasNext()) {
156 PolicyItem inItem = inListItr.next();
157 // check for trigger policy (no parent)
158 String parent = inItem.getParentPolicy();
159 if (parent == null || parent.length() == 0) {
160 if (!outList.isEmpty()) {
161 throw new BadRequestException(
162 "Operation Policy validation problem: more than one trigger policy");
168 // check if this PolicyItem's parent has been processed
169 for (PolicyItem outItem : outList) {
170 if (outItem.getId().equals(parent)) {
171 // if the inItem parent is already in the outList,
172 // then add inItem to outList and remove from inList
184 protected static void validate(Results results) {
185 if (results.isValid()) {
186 logger.info("results.getSpecification()=" + results.getSpecification());
188 // throw exception with error info
189 StringBuilder sb = new StringBuilder();
190 sb.append("Operation Policy validation problem: ControlLoopPolicyBuilder failed with following messages: ");
191 for (Message message : results.getMessages()) {
192 sb.append(message.getMessage());
195 throw new BadRequestException(sb.toString());
200 protected static Resource[] convertToResources(List<String> stringList, ResourceType resourceType) {
201 if (stringList == null || stringList.isEmpty()) {
202 return new Resource[0];
204 return stringList.stream().map(stringElem -> new Resource(stringElem, resourceType)).toArray(Resource[]::new);
207 protected static PolicyResult[] convertToPolicyResults(List<String> prList) {
208 if (prList == null || prList.isEmpty()) {
209 return new PolicyResult[0];
211 return prList.stream().map(PolicyResult::toResult).toArray(PolicyResult[]::new);