90120288bc66617988e225002c679d960cb9dd07
[sdc.git] /
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.be.components.distribution.engine;
22
23 import java.util.ArrayList;
24 import java.util.Collection;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Optional;
28 import java.util.stream.Collectors;
29
30 import javax.annotation.PostConstruct;
31
32 import org.openecomp.sdc.be.config.ConfigurationManager;
33 import org.openecomp.sdc.be.model.ArtifactDefinition;
34 import org.openecomp.sdc.be.model.ComponentInstance;
35 import org.openecomp.sdc.be.model.ComponentParametersView;
36 import org.openecomp.sdc.be.model.Resource;
37 import org.openecomp.sdc.be.model.Service;
38 import org.openecomp.sdc.be.model.category.CategoryDefinition;
39 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
40 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
41 import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
42 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
43 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
44 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
45 import org.slf4j.Logger;
46 import org.slf4j.LoggerFactory;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.stereotype.Component;
49
50 import fj.data.Either;
51
52 @Component("serviceDistributionArtifactsBuilder")
53 public class ServiceDistributionArtifactsBuilder {
54
55         private int defaultArtifactInstallTimeout = 60;
56
57         private static Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class.getName());
58
59         final static String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
60         final static String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s";
61         final static String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
62
63         final static String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s";
64
65         @javax.annotation.Resource
66         InterfaceLifecycleOperation interfaceLifecycleOperation;
67
68         @javax.annotation.Resource
69         IArtifactOperation artifactOperation;
70         
71         @Autowired
72         ToscaOperationFacade toscaOperationFacade;
73
74         /*
75          * @javax.annotation.Resource private
76          * InformationDeployedArtifactsBusinessLogic
77          * informationDeployedArtifactsBusinessLogic;
78          */
79
80         @PostConstruct
81         private void init() {
82                 defaultArtifactInstallTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
83                                 .getDefaultHeatArtifactTimeoutMinutes();
84         }
85
86         public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
87                 return interfaceLifecycleOperation;
88         }
89
90         public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) {
91                 this.interfaceLifecycleOperation = interfaceLifecycleOperation;
92         }
93
94         public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId) {
95                 INotificationData notificationData = new NotificationDataImpl();
96
97                 notificationData.setResources(convertRIToJsonContanier(service));
98                 notificationData.setServiceName(service.getName());
99                 notificationData.setServiceVersion(service.getVersion());
100                 notificationData.setDistributionID(distributionId);
101                 notificationData.setServiceUUID(service.getUUID());
102                 notificationData.setServiceDescription(service.getDescription());
103                 notificationData.setServiceInvariantUUID(service.getInvariantUUID());
104
105                 logger.debug("Before returning notification data object {}", notificationData);
106
107                 return notificationData;
108
109         }
110
111         public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) {
112
113                 notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service));
114
115                 logger.debug("Before returning notification data object {}", notificationData);
116
117                 return notificationData;
118
119         }
120
121         private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
122                 
123                 Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
124                 List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream()
125                                 //filters all artifacts with existing EsId
126                                 .filter(artifactDef -> artifactDef.checkEsIdExist())
127                                 //collects all filtered artifacts with existing EsId to List
128                                 .collect(Collectors.toList());
129                 
130                 Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service);
131                 if(toscaTemplateArtifactOptl.isPresent()){
132                         extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get());
133                 }
134                 
135                 Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service);
136                 if(toscaCsarArtifactOptl.isPresent()){
137                         extractedServiceArtifacts.add(toscaCsarArtifactOptl.get());
138                 }
139                 
140                 List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts);
141                 return artifacts;
142         }
143
144         private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) {
145                 return service.getToscaArtifacts().values().stream()
146                                 //filters TOSCA_TEMPLATE artifact
147                                 .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
148         }
149         
150         private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) {
151                 return service.getToscaArtifacts().values().stream()
152                                 //filters TOSCA_CSAR artifact
153                                 .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
154         }
155
156         private List<JsonContainerResourceInstance> convertRIToJsonContanier(Service service) {
157                 List<JsonContainerResourceInstance> ret = new ArrayList<JsonContainerResourceInstance>();
158                 if (service.getComponentInstances() != null) {
159                         for (ComponentInstance resourceInstance : service.getComponentInstances()) {
160                                 String resoucreType = resourceInstance.getOriginType().getValue();
161                                 List<ArtifactDefinition> artifactsDefList = getArtifactsWithPayload(resourceInstance);
162                                 List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance,
163                                                 artifactsDefList);
164
165                                 String resourceInvariantUUID = null;
166                                 String resourceCategory = null;
167                                 String resourceSubcategory = null;
168
169                                 ComponentParametersView componentParametersView = new ComponentParametersView();
170                                 componentParametersView.disableAll();
171                                 componentParametersView.setIgnoreCategories(false);
172                                 Either<Resource, StorageOperationStatus> componentResponse = toscaOperationFacade
173                                                 .getToscaElement(resourceInstance.getComponentUid(), componentParametersView);
174
175                                 if (componentResponse.isRight()) {
176                                         logger.debug("Resource {} Invariant UUID & Categories retrieving failed", resourceInstance.getComponentUid());
177                                 } else {
178                                         Resource resource = componentResponse.left().value();
179                                         resourceInvariantUUID = resource.getInvariantUUID();
180
181                                         List<CategoryDefinition> categories = resource.getCategories();
182
183                                         if (categories != null) {
184                                                 CategoryDefinition categoryDefinition = categories.get(0);
185
186                                                 if (categoryDefinition != null) {
187                                                         resourceCategory = categoryDefinition.getName();
188                                                         List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
189                                                         if (null != subcategories) {
190                                                                 SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
191
192                                                                 if (subCategoryDefinition != null) {
193                                                                         resourceSubcategory = subCategoryDefinition.getName();
194                                                                 }
195                                                         }
196                                                 }
197                                         }
198                                 }
199
200                                 JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(resourceInstance, resoucreType,
201                                                 artifacts);
202                                 jsonContainer.setResourceInvariantUUID(resourceInvariantUUID);
203                                 jsonContainer.setCategory(resourceCategory);
204                                 jsonContainer.setSubcategory(resourceSubcategory);
205                                 ret.add(jsonContainer);
206                         }
207                 }
208                 return ret;
209         }
210
211         private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) {
212                 List<ArtifactDefinition> ret = new ArrayList<ArtifactDefinition>();
213
214                 // List<ArtifactDefinition> informationDeployedArtifacts =
215                 // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance);
216                 List<ArtifactDefinition> deployableArtifacts = new ArrayList<ArtifactDefinition>();
217                 // deployableArtifacts.addAll(informationDeployedArtifacts);
218                 if (resourceInstance.getDeploymentArtifacts() != null) {
219                         deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values());
220                 }
221
222                 for (ArtifactDefinition artifactDef : deployableArtifacts) {
223                         if (artifactDef.checkEsIdExist()) {
224                                 ret.add(artifactDef);
225                         }
226                 }
227
228                 return ret;
229         }
230
231         /**
232          * build the url for resource intance artifact
233          * 
234          * @param service
235          * @param resourceData
236          * @param artifactName
237          * @return
238          */
239         public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance,
240                         String artifactName) {
241
242                 String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
243                                 resourceInstance.getNormalizedName(), artifactName);
244
245                 logger.debug("After building artifact url {}", url);
246
247                 return url;
248         }
249
250         /**
251          * build the url for resource intance artifact
252          * 
253          * @param service
254          * @param resourceData
255          * @param artifactName
256          * @return
257          */
258         public static String buildServiceArtifactUrl(Service service, String artifactName) {
259
260                 String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName);
261
262                 logger.debug("After building artifact url {}", url);
263
264                 return url;
265
266         }
267
268         /**
269          * Retrieve all deployment artifacts of all resources under a given service
270          * 
271          * @param resourceArtifactsResult
272          * @param service
273          * @param deConfiguration
274          * @return
275          */
276         public Either<Boolean, StorageOperationStatus> isServiceContainsDeploymentArtifacts(Service service) {
277
278                 Either<Boolean, StorageOperationStatus> result = Either.left(false);
279                 Map<String, ArtifactDefinition> serviseArtifactsMap = service.getDeploymentArtifacts();
280                 if (serviseArtifactsMap != null && !serviseArtifactsMap.isEmpty()) {
281                         result = Either.left(true);
282                         return result;
283                 }
284
285                 List<ComponentInstance> resourceInstances = service.getComponentInstances();
286
287                 if (resourceInstances != null) {
288                         for (ComponentInstance resourceInstance : resourceInstances) {
289
290                                 Map<String, ArtifactDefinition> deploymentArtifactsMapper = resourceInstance.getDeploymentArtifacts();
291                                 // List<ArtifactDefinition> informationDeployedArtifacts =
292                                 // informationDeployedArtifactsBusinessLogic.getInformationalDeployedArtifactsForResourceInstance(resourceInstance);
293
294                                 boolean isDeployableArtifactFound = isContainsPayload(deploymentArtifactsMapper.values());// ||
295                                                                                                                                                                                                                         // isContainsPayload(informationDeployedArtifacts);
296                                 if (isDeployableArtifactFound) {
297                                         result = Either.left(true);
298                                         break;
299                                 }
300
301                         }
302
303                 }
304
305                 return result;
306         }
307
308         private boolean isContainsPayload(Collection<ArtifactDefinition> collection) {
309                 boolean payLoadFound = collection != null && collection.stream().anyMatch(p -> p.checkEsIdExist());
310                 return payLoadFound;
311         }
312
313 }