02b575523cdfdf9c7ce5a13e7af326dadd4cbeb8
[policy/distribution.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2018 Ericsson. All rights reserved.
4  * ================================================================================
5  * Licensed under the Apache License, Version 2.0 (the "License");
6  * you may not use this file except in compliance with the License.
7  * You may obtain a copy of the License at
8  *
9  *      http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  *
17  * SPDX-License-Identifier: Apache-2.0
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.onap.policy.distribution.reception.decoding.pdpx;
22
23 import com.google.common.collect.ImmutableMap;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import com.google.gson.reflect.TypeToken;
27
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.Map;
32 import java.util.regex.Matcher;
33 import java.util.regex.Pattern;
34
35 import org.onap.policy.common.logging.flexlogger.FlexLogger;
36 import org.onap.policy.common.logging.flexlogger.Logger;
37 import org.onap.policy.distribution.reception.decoding.PolicyDecodingException;
38 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
39 import org.onap.sdc.toscaparser.api.CapabilityAssignment;
40 import org.onap.sdc.toscaparser.api.CapabilityAssignments;
41 import org.onap.sdc.toscaparser.api.elements.Metadata;
42 import org.onap.sdc.toscaparser.api.NodeTemplate;
43 import org.onap.sdc.toscaparser.api.RequirementAssignment;
44
45 /**
46  * Extract concerned info from NodeTemplate, currently ONLY HPA Feature.
47  *
48  * @author Libo Zhu (libo.zhu@intel.com)
49  */
50 public class ExtractFromNode {
51
52     private static final String CONFIGURATION_VALUE = "configurationValue";
53     private static final Logger LOGGER = FlexLogger.getLogger(ExtractFromNode.class);
54     private static final String VDU_TYPE = "tosca.nodes.nfv.Vdu.Compute";
55     private static final String VDU_CP_TYPE = "tosca.nodes.nfv.VduCp";
56     private static final String VIRTUAL_MEM_SIZE_PATH = "virtual_memory#virtual_mem_size";
57     private static final String NUM_VIRTUAL_CPU_PATH = "virtual_cpu#num_virtual_cpu";
58     private static final String CPU_ARCHITECTURE_PATH = "virtual_cpu#cpu_architecture";
59     private static final String MEMORY_PAGE_SIZE_PATH = "virtual_memory#vdu_memory_requirements#memoryPageSize";
60     private static final String NETWORK_INTERFACE_TYPE_PATH =
61             "virtual_network_interface_requirements#network_interface_requirements#interfaceType";
62     private static final String NETWORK_PCI_PATH = "virtual_network_interface_requirements#nic_io_requirements";
63     private static final String BASIC_CAPABILITIES_HPA_FEATURE = "BasicCapabilities";
64     private static final String HUGE_PAGES_HPA_FEATURE = "hugePages";
65     private static final Map<String, String> NETWORK_HPA_FEATURE_MAP =
66             ImmutableMap.of("SR-IOV", "SriovNICNetwork", "PCI-Passthrough", "pciePassthrough");
67
68     private ISdcCsarHelper sdcCsarHelper;
69     final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().disableHtmlEscaping().create();
70
71     public void setSdcCsarHelper(final ISdcCsarHelper sdcCsarHelper) {
72         this.sdcCsarHelper = sdcCsarHelper;
73     }
74
75     /**
76      * ExtractInfo from VNF , each VNF may includes more than one VDUs and CPs return new generated PdpxPolicy if it has
77      * got Hpa feature info or else return null.
78      *
79      * @param node the NodeTemplate
80      *
81      * @return the extracted info from input node
82      *
83      * @throws PolicyDecodingException if extract fails
84      */
85     public Content extractInfo(final NodeTemplate node) throws PolicyDecodingException {
86         Metadata metaData = sdcCsarHelper.getNodeTemplateMetadata(node);
87         LOGGER.debug("the meta data of this nodetemplate = " + metaData);
88         final List<NodeTemplate> lnodeChild = sdcCsarHelper.getNodeTemplateChildren(node);
89         LOGGER.debug("the size of lnodeChild = " + lnodeChild.size());
90
91         // Store all the VDUs under one VNF
92         final List<NodeTemplate> lnodeVdu = new ArrayList<>();
93         // Store all the Cps under one VNF
94         final List<NodeTemplate> lnodeVduCp = new ArrayList<>();
95         for (final NodeTemplate nodeChild : lnodeChild) {
96             final String type = sdcCsarHelper.getTypeOfNodeTemplate(nodeChild);
97             LOGGER.debug("the type of this nodeChild = " + type);
98             LOGGER.debug("the meta data of this nodeChild = " + sdcCsarHelper.getNodeTemplateMetadata(nodeChild));
99             if (type.equalsIgnoreCase(VDU_TYPE)) {
100                 lnodeVdu.add(nodeChild);
101             } else if (type.equalsIgnoreCase(VDU_CP_TYPE)) {
102                 lnodeVduCp.add(nodeChild);
103             }
104         }
105         LOGGER.debug("the size of vdu is =" + lnodeVdu.size());
106         LOGGER.debug("the size of cp is =" + lnodeVduCp.size());
107
108         final Content content = new Content();
109         content.setResources(metaData.getValue("name"));
110         content.setIdentity(content.getPolicyType() + "_" + content.getResources());
111         extractInfoVdu(lnodeVdu, content);
112         extractInfoVduCp(lnodeVduCp, content);
113         if (content.getFlavorFeatures().isEmpty()) {
114             return null;
115         }
116         return content;
117     }
118
119
120     /**
121      * ExtractInfofromVdu, supported hpa features, All under the capability of tosca.nodes.nfv.Vdu.Compute.
122      *
123      * @param lnodeVdu the list of Vdu node
124      *
125      * @param content to be change based on lnodeVdu
126      */
127     public void extractInfoVdu(final List<NodeTemplate> lnodeVdu, final Content content) {
128         // each VDU <=> FlavorFeature
129         for (final NodeTemplate node : lnodeVdu) {
130             final Attribute flavorAttribute = new Attribute();
131             flavorAttribute.setAttributeName("flavorName");
132             flavorAttribute.setAttributeValue("");
133             final Directive flavorDirective = new Directive();
134             flavorDirective.setType("flavor_directives");
135             flavorDirective.getAttributes().add(flavorAttribute);
136             final FlavorFeature flavorFeature = new FlavorFeature();
137             flavorFeature.setId(sdcCsarHelper.getNodeTemplatePropertyLeafValue(node, "name"));
138             flavorFeature.getDirectives().add(flavorDirective);
139
140             final CapabilityAssignments capabilityAssignments = sdcCsarHelper.getCapabilitiesOf(node);
141             final CapabilityAssignment capabilityAssignment =
142                     capabilityAssignments.getCapabilityByName("virtual_compute");
143             if (capabilityAssignment != null) {
144                 generateBasicCapability(capabilityAssignment, flavorFeature);
145                 generateHugePages(capabilityAssignment, flavorFeature);
146             }
147             content.getFlavorFeatures().add(flavorFeature);
148         }
149     }
150
151     /**
152      * GenerateBasicCapability, supported hpa features, All under the capability of tosca.nodes.nfv.Vdu.Compute.
153      *
154      * @param capabilityAssignment represents the capability of node
155      *
156      * @param flavorFeature represents all the features of specified flavor
157      */
158     private void generateBasicCapability(final CapabilityAssignment capabilityAssignment,
159             final FlavorFeature flavorFeature) {
160         // the format is xxx MB/GB like 4096 MB
161         final String virtualMemSize =
162                 sdcCsarHelper.getCapabilityPropertyLeafValue(capabilityAssignment, VIRTUAL_MEM_SIZE_PATH);
163         if (virtualMemSize != null) {
164             LOGGER.debug("the virtualMemSize = " + virtualMemSize);
165             final HpaFeatureAttribute hpaFeatureAttribute =
166                     generateHpaFeatureAttribute("virtualMemSize", virtualMemSize);
167             final FlavorProperty flavorProperty = new FlavorProperty();
168             flavorProperty.setHpaFeature(BASIC_CAPABILITIES_HPA_FEATURE);
169             flavorProperty.getHpaFeatureAttributes().add(hpaFeatureAttribute);
170             flavorFeature.getFlavorProperties().add(flavorProperty);
171         }
172
173         // the format is int like 2
174         final String numVirtualCpu =
175                 sdcCsarHelper.getCapabilityPropertyLeafValue(capabilityAssignment, NUM_VIRTUAL_CPU_PATH);
176         if (numVirtualCpu != null) {
177             LOGGER.debug("the numVirtualCpu = " + numVirtualCpu);
178             final HpaFeatureAttribute hpaFeatureAttribute = generateHpaFeatureAttribute("numVirtualCpu", numVirtualCpu);
179             final String cpuArchitecture =
180                     sdcCsarHelper.getCapabilityPropertyLeafValue(capabilityAssignment, CPU_ARCHITECTURE_PATH);
181             final FlavorProperty flavorProperty = new FlavorProperty();
182             flavorProperty.setHpaFeature(BASIC_CAPABILITIES_HPA_FEATURE);
183             if (cpuArchitecture != null) {
184                 flavorProperty.setArchitecture(cpuArchitecture);
185             }
186             flavorProperty.getHpaFeatureAttributes().add(hpaFeatureAttribute);
187             flavorFeature.getFlavorProperties().add(flavorProperty);
188         }
189     }
190
191     /**
192      * GenerateHpaFeatureAttribute based on the value of featureValue. the format: "hpa-attribute-key": "pciVendorId",
193      * "hpa-attribute-value": "1234", "operator": "=", "unit": "xxx".
194      *
195      * @param hpaAttributeKey get from the high layer tosca DM
196      *
197      * @param featureValue get from the high layer tosca DM
198      *
199      */
200     private HpaFeatureAttribute generateHpaFeatureAttribute(final String hpaAttributeKey, final String featureValue) {
201         // based on input featureValue, return back a suitable hpaFeatureAttribute
202         final HpaFeatureAttribute hpaFeatureAttribute = new HpaFeatureAttribute();
203         hpaFeatureAttribute.setHpaAttributeKey(hpaAttributeKey);
204         final String tmp = featureValue.replace(" ", "");
205         final String pattern = "(\\D*)(\\d+)(\\D*)";
206         final Pattern r = Pattern.compile(pattern);
207         final Matcher m = r.matcher(tmp);
208         if (m.find()) {
209             LOGGER.debug("operator = " + m.group(1));
210             LOGGER.debug("value = " + m.group(2));
211             LOGGER.debug("unit = " + m.group(3));
212             hpaFeatureAttribute.setOperator(m.group(1));
213             hpaFeatureAttribute.setHpaAttributeValue(m.group(2));
214             hpaFeatureAttribute.setUnit(m.group(3));
215         }
216         return hpaFeatureAttribute;
217     }
218
219     /**
220      * GenerateHugePages, supported hpa features, All under the capability of tosca.nodes.nfv.Vdu.Compute. The format is
221      * a map like: {"schemaVersion": "0", "schemaSelector": "", "hardwarePlatform": "generic", "mandatory": "true",
222      * "configurationValue": "2 MB"}
223      *
224      * @param capabilityAssignment represents the capability of node
225      *
226      * @param flavorFeature represents all the features of specified flavor
227      */
228     private void generateHugePages(final CapabilityAssignment capabilityAssignment, final FlavorFeature flavorFeature) {
229         final String memoryPageSize =
230                 sdcCsarHelper.getCapabilityPropertyLeafValue(capabilityAssignment, MEMORY_PAGE_SIZE_PATH);
231         LOGGER.debug("the memoryPageSize = " + memoryPageSize);
232         if (memoryPageSize != null) {
233             final Map<String, String> retMap =
234                     gson.fromJson(memoryPageSize, new TypeToken<HashMap<String, String>>() {}.getType());
235             LOGGER.debug("the retMap = " + retMap);
236             final String memoryPageSizeValue = retMap.get(CONFIGURATION_VALUE);
237             final String mandatory = retMap.get("mandatory");
238             if (memoryPageSizeValue == null) {
239                 return;
240             }
241             final HpaFeatureAttribute hpaFeatureAttribute =
242                     generateHpaFeatureAttribute("memoryPageSize", memoryPageSizeValue);
243             final FlavorProperty flavorProperty = new FlavorProperty();
244             flavorProperty.setHpaFeature(HUGE_PAGES_HPA_FEATURE);
245             if (mandatory != null) {
246                 flavorProperty.setMandatory(mandatory);
247             }
248             flavorProperty.getHpaFeatureAttributes().add(hpaFeatureAttribute);
249             flavorFeature.getFlavorProperties().add(flavorProperty);
250         }
251     }
252
253     /**
254      * ExtractInfoVduCp, supported hpa features, under the virtual_network_interface_requirements of
255      * tosca.nodes.nfv.VduCp.
256      *
257      * @param lnodeVduCp the list of VduCp node
258      *
259      * @param content to be change based on lnodeVduCp
260      * @throws PolicyDecodingException if extract CP fails
261      */
262     public void extractInfoVduCp(final List<NodeTemplate> lnodeVduCp, final Content content)
263             throws PolicyDecodingException {
264         // each CP will binds to a VDU so need the vdu flavor map info.
265         final Map<String, FlavorFeature> vduFlavorMap = new HashMap<>();
266         for (final FlavorFeature flavorFeature : content.getFlavorFeatures()) {
267             LOGGER.debug("the id = " + flavorFeature.getId());
268             vduFlavorMap.put(flavorFeature.getId(), flavorFeature);
269         }
270         for (final NodeTemplate node : lnodeVduCp) {
271             final String interfaceType =
272                     sdcCsarHelper.getNodeTemplatePropertyLeafValue(node, NETWORK_INTERFACE_TYPE_PATH);
273             LOGGER.debug("the interfaceType = " + interfaceType);
274             Map<String, Object> retMap = new HashMap<>();
275             if (interfaceType != null) {
276                 retMap = gson.fromJson(interfaceType, new TypeToken<HashMap<String, Object>>() {}.getType());
277                 LOGGER.debug("the retMap = " + retMap);
278             }
279
280             String networkHpaFeature;
281             if (retMap.containsKey(CONFIGURATION_VALUE)) {
282                 final String interfaceTypeValue = retMap.get(CONFIGURATION_VALUE).toString();
283                 LOGGER.debug(" the interfacetype value is =" + interfaceTypeValue);
284                 if (NETWORK_HPA_FEATURE_MAP.containsKey(interfaceTypeValue)) {
285                     networkHpaFeature = NETWORK_HPA_FEATURE_MAP.get(interfaceTypeValue);
286                     LOGGER.debug(" the networkHpaFeature is =" + networkHpaFeature);
287                 } else {
288                     LOGGER.debug(" unspported network interface ");
289                     return;
290                 }
291             } else {
292                 LOGGER.debug(" no configurationValue defined in interfaceType");
293                 return;
294             }
295
296             for (final RequirementAssignment requriement : sdcCsarHelper.getRequirementsOf(node).getAll()) {
297                 final String nodeTemplateName = requriement.getNodeTemplateName().toLowerCase();
298                 LOGGER.debug("getNodeTemplateName =" + nodeTemplateName);
299                 if (nodeTemplateName == null) {
300                     continue;
301                 }
302                 if (!vduFlavorMap.containsKey(nodeTemplateName)) {
303                     throw new PolicyDecodingException("vdu Flavor Map should contains the key " + nodeTemplateName);
304                 }
305                 generateNetworkFeature(networkHpaFeature, node, vduFlavorMap.get(nodeTemplateName));
306             }
307         }
308     }
309
310     /**
311      * GenerateNetworkFeature, all pci feature are grouped into FlavorFeature together. The format is a map like:
312      * {"schemaVersion": "0", "schemaSelector": "", "hardwarePlatform": "generic", "mandatory": "true",
313      * "configurationValue": "2 MB"}
314      *
315      * @param networkHpaFeature represents the specified Hpa feature
316      * @param node represents the CP Node
317      * @param flavorFeature represents all the features of specified flavor
318      */
319     private void generateNetworkFeature(final String networkHpaFeature, final NodeTemplate node,
320             final FlavorFeature flavorFeature) {
321         final FlavorProperty flavorProperty = new FlavorProperty();
322         flavorProperty.setHpaFeature(networkHpaFeature);
323         final String[] pciKeys = { "pciVendorId", "pciDeviceId", "pciNumDevices", "physicalNetwork" };
324         for (final String pciKey : pciKeys) {
325             LOGGER.debug("the pciKey = " + pciKey);
326             final String pciKeyPath = NETWORK_PCI_PATH + "#" + pciKey;
327             final String pciValue = sdcCsarHelper.getNodeTemplatePropertyLeafValue(node, pciKeyPath);
328             if (pciValue != null) {
329                 LOGGER.debug("the pciValue = " + pciValue);
330                 final Map<String, String> retMap =
331                         gson.fromJson(pciValue, new TypeToken<HashMap<String, String>>() {}.getType());
332                 final String pciConfigValue = retMap.get(CONFIGURATION_VALUE);
333                 if (pciConfigValue == null) {
334                     return;
335                 }
336                 final HpaFeatureAttribute hpaFeatureAttribute = generateHpaFeatureAttribute(pciKey, pciConfigValue);
337                 flavorProperty.getHpaFeatureAttributes().add(hpaFeatureAttribute);
338             }
339         }
340         flavorFeature.getFlavorProperties().add(flavorProperty);
341     }
342 }