Sync Integ to Master
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / components / distribution / engine / ServiceDistributionArtifactsBuilder.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.be.components.distribution.engine;
22
23 import fj.data.Either;
24
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.openecomp.sdc.be.config.ConfigurationManager;
28 import org.openecomp.sdc.be.model.*;
29 import org.openecomp.sdc.be.model.category.CategoryDefinition;
30 import org.openecomp.sdc.be.model.category.SubCategoryDefinition;
31 import org.openecomp.sdc.be.model.jsontitan.operations.ToscaOperationFacade;
32 import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
33 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
34 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
35 import org.slf4j.Logger;
36 import org.slf4j.LoggerFactory;
37 import org.springframework.beans.factory.annotation.Autowired;
38 import org.springframework.stereotype.Component;
39
40 import java.util.*;
41 import java.util.stream.Collectors;
42
43 @Component("serviceDistributionArtifactsBuilder")
44 public class ServiceDistributionArtifactsBuilder {
45
46     private static final Logger logger = LoggerFactory.getLogger(ServiceDistributionArtifactsBuilder.class);
47
48     static final String BASE_ARTIFACT_URL = "/sdc/v1/catalog/services/%s/%s/";
49     static final String RESOURCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resources/%s/%s/artifacts/%s";
50     static final String SERVICE_ARTIFACT_URL = BASE_ARTIFACT_URL + "artifacts/%s";
51     static final String RESOURCE_INSTANCE_ARTIFACT_URL = BASE_ARTIFACT_URL + "resourceInstances/%s/artifacts/%s";
52
53     @javax.annotation.Resource
54     InterfaceLifecycleOperation interfaceLifecycleOperation;
55
56     @javax.annotation.Resource
57     IArtifactOperation artifactOperation;
58
59     @Autowired
60     ToscaOperationFacade toscaOperationFacade;
61
62     public InterfaceLifecycleOperation getInterfaceLifecycleOperation() {
63         return interfaceLifecycleOperation;
64     }
65
66     public void setInterfaceLifecycleOperation(InterfaceLifecycleOperation interfaceLifecycleOperation) {
67         this.interfaceLifecycleOperation = interfaceLifecycleOperation;
68     }
69
70     private String resolveWorkloadContext(String workloadContext) {
71         return workloadContext != null ? workloadContext :
72                 ConfigurationManager.getConfigurationManager().getConfiguration().getWorkloadContext();
73     }
74
75     public INotificationData buildResourceInstanceForDistribution(Service service, String distributionId, String workloadContext) {
76         INotificationData notificationData = new NotificationDataImpl();
77
78         notificationData.setResources(convertRIsToJsonContanier(service));
79         notificationData.setServiceName(service.getName());
80         notificationData.setServiceVersion(service.getVersion());
81         notificationData.setDistributionID(distributionId);
82         notificationData.setServiceUUID(service.getUUID());
83         notificationData.setServiceDescription(service.getDescription());
84         notificationData.setServiceInvariantUUID(service.getInvariantUUID());
85         workloadContext = resolveWorkloadContext(workloadContext);
86         if (workloadContext!=null){
87             notificationData.setWorkloadContext(workloadContext);
88         }
89         logger.debug("Before returning notification data object {}", notificationData);
90
91         return notificationData;
92     }
93
94     public INotificationData buildServiceForDistribution(INotificationData notificationData, Service service) {
95
96         notificationData.setServiceArtifacts(convertServiceArtifactsToArtifactInfo(service));
97
98         logger.debug("Before returning notification data object {}", notificationData);
99
100         return notificationData;
101     }
102
103     private List<ArtifactInfoImpl> convertServiceArtifactsToArtifactInfo(Service service) {
104
105         Map<String, ArtifactDefinition> serviceArtifactsMap = service.getDeploymentArtifacts();
106         List<ArtifactDefinition> extractedServiceArtifacts = serviceArtifactsMap.values().stream()
107                 //filters all artifacts with existing EsId
108                 .filter(ArtifactDefinition::checkEsIdExist)
109                 //collects all filtered artifacts with existing EsId to List
110                 .collect(Collectors.toList());
111
112         Optional<ArtifactDefinition> toscaTemplateArtifactOptl = exrtactToscaTemplateArtifact(service);
113         if(toscaTemplateArtifactOptl.isPresent()){
114             extractedServiceArtifacts.add(toscaTemplateArtifactOptl.get());
115         }
116
117         Optional<ArtifactDefinition> toscaCsarArtifactOptl = exrtactToscaCsarArtifact(service);
118         if(toscaCsarArtifactOptl.isPresent()){
119             extractedServiceArtifacts.add(toscaCsarArtifactOptl.get());
120         }
121
122         return ArtifactInfoImpl.convertServiceArtifactToArtifactInfoImpl(service, extractedServiceArtifacts);
123     }
124
125     private Optional<ArtifactDefinition> exrtactToscaTemplateArtifact(Service service) {
126         return service.getToscaArtifacts().values().stream()
127                 //filters TOSCA_TEMPLATE artifact
128                 .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_TEMPLATE.getType())).findAny();
129     }
130
131     private Optional<ArtifactDefinition> exrtactToscaCsarArtifact(Service service) {
132         return service.getToscaArtifacts().values().stream()
133                 //filters TOSCA_CSAR artifact
134                 .filter(e -> e.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())).findAny();
135     }
136
137     private List<JsonContainerResourceInstance> convertRIsToJsonContanier(Service service) {
138         List<JsonContainerResourceInstance> ret = new ArrayList<>();
139         if (service.getComponentInstances() != null) {
140             for (ComponentInstance instance : service.getComponentInstances()) {
141                 JsonContainerResourceInstance jsonContainer = new JsonContainerResourceInstance(instance, convertToArtifactsInfoImpl(service, instance));
142                 ComponentParametersView filter = new ComponentParametersView();
143                 filter.disableAll();
144                 filter.setIgnoreCategories(false);
145                 toscaOperationFacade.getToscaElement(instance.getComponentUid(), filter)
146                     .left()
147                     .bind(r->{fillJsonContainer(jsonContainer, (Resource) r); return Either.left(r);})
148                     .right()
149                     .forEach(r->logger.debug("Resource {} Invariant UUID & Categories retrieving failed", instance.getComponentUid()));
150                 ret.add(jsonContainer);
151             }
152         }
153         return ret;
154     }
155
156     private void fillJsonContainer(JsonContainerResourceInstance jsonContainer, Resource resource) {
157         jsonContainer.setResourceInvariantUUID(resource.getInvariantUUID());
158         setCategories(jsonContainer, resource.getCategories());
159     }
160
161     private List<ArtifactInfoImpl> convertToArtifactsInfoImpl(Service service, ComponentInstance resourceInstance) {
162         List<ArtifactInfoImpl> artifacts = ArtifactInfoImpl.convertToArtifactInfoImpl(service, resourceInstance, getArtifactsWithPayload(resourceInstance));
163         artifacts.stream().forEach(ArtifactInfoImpl::updateArtifactTimeout);
164         return artifacts;
165     }
166
167     private void setCategories(JsonContainerResourceInstance jsonContainer, List<CategoryDefinition> categories) {
168         if (categories != null) {
169             CategoryDefinition categoryDefinition = categories.get(0);
170
171             if (categoryDefinition != null) {
172                 jsonContainer.setCategory(categoryDefinition.getName());
173                 List<SubCategoryDefinition> subcategories = categoryDefinition.getSubcategories();
174                 if (null != subcategories) {
175                     SubCategoryDefinition subCategoryDefinition = subcategories.get(0);
176
177                     if (subCategoryDefinition != null) {
178                         jsonContainer.setSubcategory(subCategoryDefinition.getName());
179                     }
180                 }
181             }
182         }
183     }
184
185     private List<ArtifactDefinition> getArtifactsWithPayload(ComponentInstance resourceInstance) {
186         List<ArtifactDefinition> ret = new ArrayList<>();
187
188         List<ArtifactDefinition> deployableArtifacts = new ArrayList<>();
189         if (resourceInstance.getDeploymentArtifacts() != null) {
190             deployableArtifacts.addAll(resourceInstance.getDeploymentArtifacts().values());
191         }
192
193         for (ArtifactDefinition artifactDef : deployableArtifacts) {
194             if (artifactDef.checkEsIdExist()) {
195                 ret.add(artifactDef);
196             }
197         }
198
199         return ret;
200     }
201
202     /**
203      * build the URL for resource instance artifact
204      *
205      * @param    service
206      * @param    resourceInstance
207      * @param    artifactName
208      * @return    URL string
209      */
210     public static String buildResourceInstanceArtifactUrl(Service service, ComponentInstance resourceInstance,
211             String artifactName) {
212
213         String url = String.format(RESOURCE_INSTANCE_ARTIFACT_URL, service.getSystemName(), service.getVersion(),
214                 resourceInstance.getNormalizedName(), artifactName);
215
216         logger.debug("After building artifact url {}", url);
217
218         return url;
219     }
220
221     /**
222      * build the URL for resource instance artifact
223      *
224      * @param    service
225      * @param    artifactName
226      * @return    URL string
227      */
228     public static String buildServiceArtifactUrl(Service service, String artifactName) {
229
230         String url = String.format(SERVICE_ARTIFACT_URL, service.getSystemName(), service.getVersion(), artifactName);
231
232         logger.debug("After building artifact url {}", url);
233
234         return url;
235
236     }
237
238     /**
239      * Verifies that the service or at least one of its instance contains deployment artifacts
240      *
241      * @param    the service
242      * @return    boolean
243      */
244     public boolean verifyServiceContainsDeploymentArtifacts(Service service) {
245         if (MapUtils.isNotEmpty(service.getDeploymentArtifacts())) {
246             return true;
247         }
248         boolean contains = false;
249         List<ComponentInstance> resourceInstances = service.getComponentInstances();
250         if (CollectionUtils.isNotEmpty(resourceInstances)) {
251             contains = resourceInstances.stream().anyMatch(i -> isContainsPayload(i.getDeploymentArtifacts()));
252         }
253         return contains;
254     }
255
256     private boolean isContainsPayload(Map<String, ArtifactDefinition> deploymentArtifacts) {
257        return deploymentArtifacts != null && deploymentArtifacts.values().stream().anyMatch(ArtifactDefinition::checkEsIdExist);
258     }
259
260 }