summaryrefslogtreecommitdiffstats
path: root/src/main/java/org/onap/clamp/clds/client/req/policy/OperationalPolicyReq.java
blob: 434da4b6589d14cc966e62f034524731359b6975 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*-
 * ============LICENSE_START=======================================================
 * ONAP CLAMP
 * ================================================================================
 * Copyright (C) 2017-2018 AT&T Intellectual Property. All rights
 *                             reserved.
 * ================================================================================
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ============LICENSE_END============================================
 * ===================================================================
 * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 */

package org.onap.clamp.clds.client.req.policy;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFLogger.Level;
import com.att.eelf.configuration.EELFManager;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.ws.rs.BadRequestException;

import org.onap.clamp.clds.config.CldsReferenceProperties;
import org.onap.clamp.clds.model.properties.Global;
import org.onap.clamp.clds.model.properties.ModelProperties;
import org.onap.clamp.clds.model.properties.PolicyChain;
import org.onap.clamp.clds.model.properties.PolicyItem;
import org.onap.clamp.clds.model.properties.Tca;
import org.onap.policy.api.AttributeType;
import org.onap.policy.controlloop.policy.OperationsAccumulateParams;
import org.onap.policy.controlloop.policy.Policy;
import org.onap.policy.controlloop.policy.PolicyResult;
import org.onap.policy.controlloop.policy.Target;
import org.onap.policy.controlloop.policy.TargetType;
import org.onap.policy.controlloop.policy.builder.BuilderException;
import org.onap.policy.controlloop.policy.builder.ControlLoopPolicyBuilder;
import org.onap.policy.controlloop.policy.builder.Message;
import org.onap.policy.controlloop.policy.builder.Results;
import org.onap.policy.sdc.Resource;
import org.onap.policy.sdc.ResourceType;
import org.onap.policy.sdc.Service;

/**
 * Construct an Operational Policy request given CLDS objects.
 */
public class OperationalPolicyReq {

    private static final EELFLogger logger = EELFManager.getInstance().getLogger(OperationalPolicyReq.class);

    protected OperationalPolicyReq() {
    }

    /**
     * Format Operational Policy attributes.
     *
     * @param refProp
     * @param prop
     * @param modelElementId
     * @param policyChain
     * @return
     * @throws BuilderException
     * @throws UnsupportedEncodingException
     */
    public static Map<AttributeType, Map<String, String>> formatAttributes(CldsReferenceProperties refProp, ModelProperties prop,
            String modelElementId, PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException {
        Global global = prop.getGlobal();
        prop.setCurrentModelElementId(modelElementId);
        prop.setPolicyUniqueId(policyChain.getPolicyId());
        String templateName = "";
        String operationTopic = "";
        String notificationTopic = "";
        String controller = "";
        Tca tca = prop.getType(Tca.class);
        if (tca != null && tca.isFound()) {
            if (!global.getActionSet().equalsIgnoreCase("enbRecipe")) {
                throw new BadRequestException(
                        "Operation Policy validation problem: action set is not selected properly.");
            }
            templateName = refProp.getStringValue("op.eNodeB.templateName", global.getService());
            operationTopic = refProp.getStringValue("op.eNodeB.operationTopic", global.getService());
            notificationTopic = refProp.getStringValue("op.eNodeB.notificationTopic", global.getService());
            controller = refProp.getStringValue("op.eNodeB.controller", global.getService());
        } else {
            if (!global.getActionSet().equalsIgnoreCase("vnfRecipe")) {
                throw new BadRequestException(
                        "Operation Policy validation problem: Action set is not selected properly.");
            }
            templateName = refProp.getStringValue("op.templateName", global.getService());
            operationTopic = refProp.getStringValue("op.operationTopic", global.getService());
            notificationTopic = refProp.getStringValue("op.notificationTopic", global.getService());
            controller = refProp.getStringValue("op.controller", global.getService());
        }
        String recipeTopic = refProp.getStringValue("op.recipeTopic", global.getService());
        // ruleAttributes
        logger.info("templateName=" + templateName);
        logger.info("notificationTopic=" + notificationTopic);
        Map<String, String> ruleAttributes = new HashMap<>();
        ruleAttributes.put("templateName", templateName);
        ruleAttributes.put("ClosedLoopControlName", prop.getControlNameAndPolicyUniqueId());
        ruleAttributes.put("NotificationTopic", notificationTopic);
        if (operationTopic == null || operationTopic.isEmpty()) {
            logger.info("recipeTopic=" + recipeTopic);
            // if no operationTopic, then don't format yaml - use first policy
            // from list
            PolicyItem policyItem = policyChain.getPolicyItems().get(0);
            ruleAttributes.put("RecipeTopic", recipeTopic);
            String recipe = policyItem.getRecipe();
            String maxRetries = String.valueOf(policyItem.getMaxRetries());
            String retryTimeLimit = String.valueOf(policyItem.getRetryTimeLimit());
            String targetResourceId = String.valueOf(policyItem.getTargetResourceId());
            logger.info("recipe=" + recipe);
            logger.info("maxRetries=" + maxRetries);
            logger.info("retryTimeLimit=" + retryTimeLimit);
            logger.info("targetResourceId=" + targetResourceId);
            ruleAttributes.put("Recipe", recipe);
            ruleAttributes.put("MaxRetries", maxRetries);
            ruleAttributes.put("RetryTimeLimit", retryTimeLimit);
            ruleAttributes.put("ResourceId", targetResourceId);
        } else {
            logger.info("operationTopic=" + operationTopic);
            // format yaml
            String yaml = (tca != null && tca.isFound()) ? formateNodeBYaml(refProp, prop, modelElementId, policyChain)
                    : formatYaml(refProp, prop, modelElementId, policyChain);
            ruleAttributes.put("OperationTopic", operationTopic);
            ruleAttributes.put("ControlLoopYaml", yaml);
        }
        // matchingAttributes
        Map<String, String> matchingAttributes = new HashMap<>();
        matchingAttributes.put("controller", controller);
        Map<AttributeType, Map<String, String>> attributes = new HashMap<>();
        attributes.put(AttributeType.RULE, ruleAttributes);
        attributes.put(AttributeType.MATCHING, matchingAttributes);
        return attributes;
    }

    /**
     * Format Operational OpenLoop Policy yaml.
     * 
     * @param refProp
     * @param prop
     * @param modelElementId
     * @param policyChain
     * @return
     * @throws BuilderException
     * @throws UnsupportedEncodingException
     */
    protected static String formatOpenLoopYaml(CldsReferenceProperties refProp, ModelProperties prop, String modelElementId,
            PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException {
        // get property objects
        Global global = prop.getGlobal();
        prop.setCurrentModelElementId(modelElementId);
        prop.setPolicyUniqueId(policyChain.getPolicyId());
        // convert values to SDC objects
        Service service = new Service(global.getService());
        Resource[] vfResources = convertToResource(global.getResourceVf(), ResourceType.VF);
        // create builder
        ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
                policyChain.getTimeout(), service, vfResources);
        // builder.setTriggerPolicy(refProp.getStringValue("op.openloop.policy"));
        // Build the specification
        Results results = builder.buildSpecification();
        validate(results);
        return URLEncoder.encode(results.getSpecification(), "UTF-8");
    }

    /**
     * Format Operational Policy yaml.
     *
     * @param refProp
     * @param prop
     * @param modelElementId
     * @param policyChain
     * @return
     * @throws BuilderException
     * @throws UnsupportedEncodingException
     */
    protected static String formatYaml(CldsReferenceProperties refProp, ModelProperties prop, String modelElementId,
            PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException {
        // get property objects
        Global global = prop.getGlobal();
        prop.setCurrentModelElementId(modelElementId);
        prop.setPolicyUniqueId(policyChain.getPolicyId());
        // convert values to SDC objects
        Service service = new Service(global.getService());
        Resource[] vfResources = convertToResource(global.getResourceVf(), ResourceType.VF);
        Resource[] vfcResources = convertToResource(global.getResourceVfc(), ResourceType.VFC);
        // create builder
        ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
                policyChain.getTimeout(), service, vfResources);
        builder.addResource(vfcResources);
        // process each policy
        Map<String, Policy> policyObjMap = new HashMap<>();
        List<PolicyItem> policyItemList = orderParentFirst(policyChain.getPolicyItems());
        for (PolicyItem policyItem : policyItemList) {
            String policyName = policyItem.getRecipe() + " Policy";
            Target target = new Target();
            target.setType(TargetType.VM);
            target.setResourceID(policyItem.getTargetResourceId());
            Policy policyObj;
            if (policyItemList.indexOf(policyItem) == 0) {
                String policyDescription = policyItem.getRecipe()
                        + " Policy - the trigger (no parent) policy - created by CLDS";
                policyObj = builder.setTriggerPolicy(policyName, policyDescription,
                        refProp.getStringValue("op.policy.appc"), target, policyItem.getRecipe(), null,
                        policyItem.getMaxRetries(), policyItem.getRetryTimeLimit());
            } else {
                Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy());
                String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by "
                        + parentPolicyObj.getName() + " - created by CLDS";
                policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription,
                        refProp.getStringValue("op.policy.appc"), target, policyItem.getRecipe(), null,
                        policyItem.getMaxRetries(), policyItem.getRetryTimeLimit(), parentPolicyObj.getId(),
                        convertToPolicyResult(policyItem.getParentPolicyConditions()));
                logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId());
            }
            policyObjMap.put(policyItem.getId(), policyObj);
        }
        // Build the specification
        Results results = builder.buildSpecification();
        validate(results);
        return URLEncoder.encode(results.getSpecification(), "UTF-8");
    }

    /**
     * Format Operational Policy yaml.
     *
     * @param refProp
     * @param prop
     * @param modelElementId
     * @param policyChain
     * @return
     * @throws BuilderException
     * @throws UnsupportedEncodingException
     */
    protected static String formateNodeBYaml(CldsReferenceProperties refProp, ModelProperties prop, String modelElementId,
            PolicyChain policyChain) throws BuilderException, UnsupportedEncodingException {
        // get property objects
        Global global = prop.getGlobal();
        prop.setCurrentModelElementId(modelElementId);
        prop.setPolicyUniqueId(policyChain.getPolicyId());
        // convert values to SDC objects
        Service service = new Service(global.getService());
        Resource[] vfResources = convertToResource(global.getResourceVf(), ResourceType.VF);
        Resource[] vfcResources = convertToResource(global.getResourceVfc(), ResourceType.VFC);
        // create builder
        ControlLoopPolicyBuilder builder = ControlLoopPolicyBuilder.Factory.buildControlLoop(prop.getControlName(),
                policyChain.getTimeout(), service, vfResources);
        builder.addResource(vfcResources);
        // process each policy
        Map<String, Policy> policyObjMap = new HashMap<>();
        List<PolicyItem> policyItemList = addAOTSActorRecipe(refProp, global.getService(),
                policyChain.getPolicyItems());
        Policy lastPolicyObj = new Policy();
        for (PolicyItem policyItem : policyItemList) {
            Target target = new Target();
            target.setType(TargetType.VM);
            target.setResourceID(policyItem.getTargetResourceId());
            String policyName = policyItem.getRecipe() + " Policy";
            Policy policyObj;
            if (policyItemList.indexOf(policyItem) == 0) {
                // To set up time window payload for trigger policy
                Map<String, String> payloadMap = new HashMap<>();
                payloadMap.put("timeWindow", refProp.getStringValue("op.eNodeB.timeWindow"));
                String policyDescription = policyItem.getRecipe()
                        + " Policy - the trigger (no parent) policy - created by CLDS";
                policyObj = builder.setTriggerPolicy(policyName, policyDescription, policyItem.getActor(), target,
                        policyItem.getRecipe(), payloadMap, policyItem.getMaxRetries(), policyItem.getRetryTimeLimit());
            } else {
                Policy parentPolicyObj = policyObjMap.get(policyItem.getParentPolicy());
                String policyDescription = policyItem.getRecipe() + " Policy - triggered conditionally by "
                        + parentPolicyObj.getName() + " - created by CLDS";
                policyObj = builder.setPolicyForPolicyResult(policyName, policyDescription, policyItem.getActor(),
                        target, policyItem.getRecipe(), null, policyItem.getMaxRetries(),
                        policyItem.getRetryTimeLimit(), parentPolicyObj.getId(),
                        convertToPolicyResult(policyItem.getParentPolicyConditions()));
                lastPolicyObj = policyObj;
                logger.info("policyObj.id=" + policyObj.getId() + "; parentPolicyObj.id=" + parentPolicyObj.getId());
            }
            policyObjMap.put(policyItem.getId(), policyObj);
        }
        // To set up operations accumulate params
        OperationsAccumulateParams operationsAccumulateParams = new OperationsAccumulateParams();
        operationsAccumulateParams.setLimit(Integer.valueOf(refProp.getStringValue("op.eNodeB.limit")));
        operationsAccumulateParams.setPeriod(refProp.getStringValue("op.eNodeB.period"));
        builder.addOperationsAccumulateParams(lastPolicyObj.getId(), operationsAccumulateParams);
        // Build the specification
        Results results = builder.buildSpecification();
        validate(results);
        return URLEncoder.encode(results.getSpecification(), "UTF-8");
    }

    private static void validate(Results results) {
        if (results.isValid()) {
            logger.info("results.getSpecification()=" + results.getSpecification());
        } else {
            // throw exception with error info
            StringBuilder sb = new StringBuilder();
            sb.append("Operation Policy validation problem: ControlLoopPolicyBuilder failed with following messages: ");
            for (Message message : results.getMessages()) {
                sb.append(message.getMessage());
                sb.append("; ");
            }
            throw new BadRequestException(sb.toString());
        }
    }

    /**
     * Adding AOTS actor and other recipe for yaml
     *
     * @param inOrigList
     * @return
     */
    private static List<PolicyItem> addAOTSActorRecipe(CldsReferenceProperties refProp, String service, List<PolicyItem> inOrigList) {
        List<PolicyItem> outList = new ArrayList<>();
        try {
            PolicyItem policyItem = inOrigList.get(0);
            ObjectNode rootNode = (ObjectNode) refProp.getJsonTemplate("op.eNodeB.recipe", service);
            Iterator<JsonNode> itr = rootNode.get("eNodeBRecipes").elements();
            while (itr.hasNext()) {
                PolicyItem policyItemObj = (PolicyItem) policyItem.clone();
                JsonNode recipeNode = itr.next();
                policyItemObj.setId(recipeNode.path("Recipe").asText());
                policyItemObj.setActor(recipeNode.path("Actor").asText());
                policyItemObj.setRecipe(recipeNode.path("Recipe").asText());
                policyItemObj.setParentPolicy(recipeNode.path("ParentPolicy").asText());
                if (!recipeNode.path("Retry").asText().isEmpty()) {
                    policyItemObj.setMaxRetries(Integer.parseInt(recipeNode.path("Retry").asText()));
                }
                if (!recipeNode.path("TimeLimit").asText().isEmpty()) {
                    policyItemObj.setRetryTimeLimit(Integer.parseInt(recipeNode.path("TimeLimit").asText()));
                }
                if (!recipeNode.path("PPConditions").asText().isEmpty()) {
                    List<String> parentPolicyConditions = new ArrayList<>();
                    for (String ppCondition : recipeNode.path("PPConditions").asText().split(",")) {
                        parentPolicyConditions.add(ppCondition);
                    }
                    policyItemObj.setParentPolicyConditions(parentPolicyConditions);
                }
                outList.add(policyItemObj);
            }
        } catch (Exception e) {
            logger.log(Level.ERROR, "Error", e);
        }
        return outList;
    }

    /**
     * Order list of PolicyItems so that parents come before any of their
     * children
     *
     * @param inOrigList
     * @return
     */
    private static List<PolicyItem> orderParentFirst(List<PolicyItem> inOrigList) {
        List<PolicyItem> inList = new ArrayList<>();
        inList.addAll(inOrigList);
        List<PolicyItem> outList = new ArrayList<>();
        int prevSize = 0;
        while (!inList.isEmpty()) {
            // check if there's a loop in the policy chain (the inList should
            // have been reduced by at least one)
            if (inList.size() == prevSize) {
                throw new BadRequestException("Operation Policy validation problem: loop in Operation Policy chain");
            }
            prevSize = inList.size();
            // the following loop should remove at least one PolicyItem from the
            // inList
            Iterator<PolicyItem> inListItr = inList.iterator();
            while (inListItr.hasNext()) {
                PolicyItem inItem = inListItr.next();
                // check for trigger policy (no parent)
                String parent = inItem.getParentPolicy();
                if (parent == null || parent.length() == 0) {
                    if (!outList.isEmpty()) {
                        throw new BadRequestException(
                                "Operation Policy validation problem: more than one trigger policy");
                    } else {
                        outList.add(inItem);
                        inListItr.remove();
                    }
                } else {
                    // check if this PolicyItem's parent has been processed
                    for (PolicyItem outItem : outList) {
                        if (outItem.getId().equals(parent)) {
                            // if the inItem parent is already in the outList,
                            // then add inItem to outList and remove from inList
                            outList.add(inItem);
                            inListItr.remove();
                            break;
                        }
                    }
                }
            }
        }
        return outList;
    }

    /**
     * Convert a List of resource strings to an array of Resource objects.
     *
     * @param stringList
     * @param resourceType
     * @return
     */
    private static Resource[] convertToResource(List<String> stringList, ResourceType resourceType) {
        if (stringList == null || stringList.isEmpty()) {
            return new Resource[0];
        }
        return stringList.stream().map(stringElem -> new Resource(stringElem, resourceType)).toArray(Resource[]::new);
    }

    /**
     * Convert a List of policy result strings to an array of PolicyResult
     * objects.
     *
     * @param prList
     * @return
     */
    private static PolicyResult[] convertToPolicyResult(List<String> prList) {
        if (prList == null || prList.isEmpty()) {
            return new PolicyResult[0];
        }
        return prList.stream().map(stringElem -> PolicyResult.toResult(stringElem)).toArray(PolicyResult[]::new);
    }
}