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() {
62 * Format Operational OpenLoop Policy yaml.
65 * @param modelElementId
68 * @throws BuilderException
69 * @throws UnsupportedEncodingException
71 public static String formatOpenLoopYaml(ModelProperties prop, String modelElementId, PolicyChain policyChain)
72 throws BuilderException, UnsupportedEncodingException {
73 // get property objects
74 Global global = prop.getGlobal();
75 prop.setCurrentModelElementId(modelElementId);
76 prop.setPolicyUniqueId(policyChain.getPolicyId());
77 // convert values to SDC objects
78 Service service = new Service(global.getService());
79 Resource[] vfResources = convertToResources(global.getResourceVf(), ResourceType.VF);
81 ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
82 policyChain.getTimeout(), service, vfResources);
83 // builder.setTriggerPolicy(refProp.getStringValue("op.openloop.policy"));
84 // Build the specification
85 Results results = builder.buildSpecification();
87 return URLEncoder.encode(results.getSpecification(), "UTF-8");
90 public static String formatYaml(ModelProperties prop, String modelElementId, PolicyChain policyChain)
91 throws BuilderException, UnsupportedEncodingException {
92 // get property objects
93 prop.setCurrentModelElementId(modelElementId);
94 prop.setPolicyUniqueId(policyChain.getPolicyId());
97 ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
98 policyChain.getTimeout());
99 // process each policy
100 Map<String, Policy> policyObjMap = new HashMap<>();
101 List<PolicyItem> policyItemList = orderParentFirst(policyChain.getPolicyItems());
102 for (PolicyItem policyItem : policyItemList) {
103 String policyName = policyItem.getRecipe() + " Policy";
104 Target target = new Target();
105 target.setType(TargetType.VM);
106 // We can send target type as VM/VNF for most of recipes
107 if (policyItem.getRecipeLevel() != null && !policyItem.getRecipeLevel().isEmpty()) {
108 target.setType(TargetType.valueOf(policyItem.getRecipeLevel()));
110 target.setResourceID(policyItem.getTargetResourceId());
111 String actor = policyItem.getActor();
112 Map<String, String> payloadMap = policyItem.getRecipePayload();
114 if (policyItemList.indexOf(policyItem) == 0) {
115 String policyDescription = policyItem.getRecipe()
116 + " Policy - the trigger (no parent) policy - created by CLDS";
117 policyObj = builder.setTriggerPolicy(policyName, policyDescription, actor, target,
118 policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit());
120 Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy());
121 String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by "
122 + parentPolicyObj.getName() + " - created by CLDS";
123 policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, actor, target,
124 policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(),
125 parentPolicyObj.getId(), convertToPolicyResults(policyItem.getParentPolicyConditions()));
126 logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId());
128 policyObjMap.put(policyItem.getId(), policyObj);
130 // Build the specification
131 Results results = builder.buildSpecification();
133 return URLEncoder.encode(results.getSpecification(), "UTF-8");
136 protected static List<PolicyItem> orderParentFirst(List<PolicyItem> inOrigList) {
137 List<PolicyItem> inList = new ArrayList<>();
138 inList.addAll(inOrigList);
139 List<PolicyItem> outList = new ArrayList<>();
141 while (!inList.isEmpty()) {
142 // check if there's a loop in the policy chain (the inList should
143 // have been reduced by at least one)
144 if (inList.size() == prevSize) {
145 throw new BadRequestException("Operation Policy validation problem: loop in Operation Policy chain");
147 prevSize = inList.size();
148 // the following loop should remove at least one PolicyItem from the
150 Iterator<PolicyItem> inListItr = inList.iterator();
151 while (inListItr.hasNext()) {
152 PolicyItem inItem = inListItr.next();
153 // check for trigger policy (no parent)
154 String parent = inItem.getParentPolicy();
155 if (parent == null || parent.length() == 0) {
156 if (!outList.isEmpty()) {
157 throw new BadRequestException(
158 "Operation Policy validation problem: more than one trigger policy");
164 // check if this PolicyItem's parent has been processed
165 for (PolicyItem outItem : outList) {
166 if (outItem.getId().equals(parent)) {
167 // if the inItem parent is already in the outList,
168 // then add inItem to outList and remove from inList
180 protected static void validate(Results results) {
181 if (results.isValid()) {
182 logger.info("results.getSpecification()=" + results.getSpecification());
184 // throw exception with error info
185 StringBuilder sb = new StringBuilder();
186 sb.append("Operation Policy validation problem: ControlLoopPolicyBuilder failed with following messages: ");
187 for (Message message : results.getMessages()) {
188 sb.append(message.getMessage());
191 throw new BadRequestException(sb.toString());
195 protected static Resource[] convertToResources(List<String> stringList, ResourceType resourceType) {
196 if (stringList == null || stringList.isEmpty()) {
197 return new Resource[0];
199 return stringList.stream().map(stringElem -> new Resource(stringElem, resourceType)).toArray(Resource[]::new);
202 protected static PolicyResult[] convertToPolicyResults(List<String> prList) {
203 if (prList == null || prList.isEmpty()) {
204 return new PolicyResult[0];
206 return prList.stream().map(PolicyResult::toResult).toArray(PolicyResult[]::new);