Add collaboration feature
[sdc.git] / openecomp-be / lib / openecomp-sdc-translator-lib / openecomp-sdc-translator-core / src / main / java / org / openecomp / sdc / translator / services / heattotosca / impl / resourcetranslation / ResourceTranslationNovaServerGroupsImpl.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation;
22
23 import org.apache.commons.collections4.CollectionUtils;
24 import org.openecomp.sdc.heat.datatypes.model.Resource;
25 import org.openecomp.sdc.tosca.datatypes.ToscaGroupType;
26 import org.openecomp.sdc.tosca.datatypes.ToscaPolicyType;
27 import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements;
28 import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition;
29 import org.openecomp.sdc.tosca.datatypes.model.PolicyDefinition;
30 import org.openecomp.sdc.tosca.services.DataModelUtil;
31 import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo;
32 import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter;
33
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.Objects;
39 import java.util.Optional;
40
41
42 public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslationBase {
43   private static final String AFFINITY = "affinity";
44   private static final String ANTI_AFFINITY = "anti-affinity";
45   private static List<String> supportedPolicies = Arrays.asList(AFFINITY, ANTI_AFFINITY);
46
47   @Override
48   protected String generateTranslatedId(TranslateTo translateTo) {
49     return isEssentialRequirementsValid(translateTo) ? getTranslatedGroupId(
50         translateTo.getResourceId()) : null;
51   }
52
53   @Override
54   protected boolean isEssentialRequirementsValid(TranslateTo translateTo) {
55     return validatePolicyType(translateTo);
56   }
57
58   @Override
59   protected Optional<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement(
60       TranslateTo translateTo) {
61     if (isEssentialRequirementsValid(translateTo)) {
62       return Optional.of(ToscaTopologyTemplateElements.GROUP);
63     } else {
64       return Optional.empty();
65     }
66   }
67
68   private boolean validatePolicyType(TranslateTo translateTo) {
69     Map<String, Object> properties = translateTo.getResource().getProperties();
70     if (Objects.isNull(properties) || Objects.isNull(properties.get("policies"))) {
71       return true;
72     }
73
74     Object policies = properties.get("policies");
75     if (!(policies instanceof List)) {
76       return false;
77     }
78
79     for (Object policy : (List) policies) {
80       if (!isValidPolicyType(policy, translateTo.getResourceId(), translateTo.getResource())) {
81         return false;
82       }
83     }
84     return true;
85   }
86
87   private boolean isValidPolicyType(Object policy, String resourceId, Resource resource) {
88     if (!(policy instanceof String)) {
89       return false;
90     }
91
92     if ((policy instanceof String) && !supportedPolicies.contains(policy)) {
93       logger.warn("Resource '" + resourceId + "'(" + resource.getType()
94           + ")  contains unsupported policy '" + policy.toString()
95           + "'. This resource is been ignored during the translation");
96       return false;
97     }
98
99     return true;
100   }
101
102   @Override
103   protected void translate(TranslateTo translateTo) {
104     mdcDataDebugMessage.debugEntryMessage(null, null);
105
106     String resourceId = translateTo.getResourceId();
107     List<String> toscaPolicyTypes = getToscaPolicies(translateTo.getResource(), resourceId);
108     if (!CollectionUtils.isEmpty(toscaPolicyTypes)) {
109       String translatedGroupId = addGroupToTopology(translateTo, resourceId);
110       addPoliciesToTopology(translateTo, translatedGroupId, toscaPolicyTypes);
111     }
112
113     mdcDataDebugMessage.debugExitMessage(null, null);
114   }
115
116   private void addPoliciesToTopology(TranslateTo translateTo, String policyTargetEntityId,
117                                      List<String> toscaPolicyTypes) {
118     mdcDataDebugMessage.debugEntryMessage(null, null);
119
120     logger.info("******** Start creating policies for resource '%s' ********",
121         translateTo.getResourceId());
122     for (int i = 0; i < toscaPolicyTypes.size(); i++) {
123       String policy = toscaPolicyTypes.get(i);
124       logger.info("******** Creating policy '%s' ********", policy);
125       PolicyDefinition policyDefinition = new PolicyDefinition();
126       policyDefinition.setType(policy);
127       policyDefinition.setTargets(Arrays.asList(policyTargetEntityId));
128       policyDefinition.setProperties(TranslatorHeatToToscaPropertyConverter
129           .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),
130               translateTo.getResourceId(),translateTo.getResource().getProperties(),
131               policyDefinition.getProperties(), translateTo.getHeatFileName(),
132               translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(),
133               policyDefinition, translateTo.getContext()));
134       policyDefinition.getProperties().put(
135           policy.equals(ToscaPolicyType.PLACEMENT_ANTILOCATE) ? "container_type"
136               : AFFINITY, "host");
137       String policyId = getTranslatedPolicyId(translateTo, toscaPolicyTypes, i);
138       DataModelUtil
139           .addPolicyDefinition(translateTo.getServiceTemplate(), policyId, policyDefinition);
140       logger.info("******** Policy '%s' created ********", policy);
141     }
142
143     logger
144         .info("******** All policies for resource '%s' created successfully ********",
145             translateTo.getResourceId());
146
147     mdcDataDebugMessage.debugExitMessage(null, null);
148   }
149
150   private String getTranslatedPolicyId(TranslateTo translateTo, List<String> toscaPolicyTypes,
151                                        int policyIndex) {
152     mdcDataDebugMessage.debugEntryMessage(null, null);
153
154     mdcDataDebugMessage.debugExitMessage(null, null);
155     return translateTo.getResourceId() + (toscaPolicyTypes.size() > 1 ? policyIndex : "")
156         + "_policy";
157   }
158
159   private String addGroupToTopology(TranslateTo translateTo, String resourceId) {
160     mdcDataDebugMessage.debugEntryMessage(null, null);
161
162     logger.info("******** Start creating group for resource '%s' ********", resourceId);
163     GroupDefinition group = new GroupDefinition();
164     group.setMembers(new ArrayList<>());
165     group.setType(ToscaGroupType.NATIVE_ROOT);
166     String translatedGroupId = getTranslatedGroupId(resourceId);
167     DataModelUtil
168         .addGroupDefinitionToTopologyTemplate(translateTo.getServiceTemplate(),
169             translatedGroupId, group);
170     logger.info("******** Creating group '%s' for resource '%s' ********", resourceId, resourceId);
171
172     mdcDataDebugMessage.debugExitMessage(null, null);
173     return translatedGroupId;
174   }
175
176   private String getTranslatedGroupId(String resourceId) {
177     return resourceId + "_group";
178   }
179
180   private List<String> getToscaPolicies(Resource resource, String resourceId) {
181     mdcDataDebugMessage.debugEntryMessage(null, null);
182
183     Map<String, Object> properties = resource.getProperties();
184     if (Objects.isNull(properties) || Objects.isNull(properties.get("policies"))) {
185       return Arrays.asList(ToscaPolicyType.PLACEMENT_ANTILOCATE);
186     }
187
188     List<Object> policies = (List) properties.get("policies");
189     List<String> retList = new ArrayList<>();
190     policies.forEach(policy -> {
191       if (isValidPolicyType(policy, resourceId, resource)) {
192         retList.add(getToscaPolicyByHotPolicy(policy));
193       }
194     });
195
196     mdcDataDebugMessage.debugExitMessage(null, null);
197     return retList;
198   }
199
200   private String getToscaPolicyByHotPolicy(Object policy) {
201     if (Objects.equals(policy, AFFINITY)) {
202       return ToscaPolicyType.PLACEMENT_COLOCATE;
203     } else {
204       return ToscaPolicyType.PLACEMENT_ANTILOCATE;
205     }
206   }
207
208 }