Sync Integ to Master
[sdc.git] / catalog-be / src / main / java / org / openecomp / sdc / be / distribution / DistributionBusinessLogic.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.distribution;
22
23 import com.google.gson.Gson;
24 import com.google.gson.GsonBuilder;
25 import fj.data.Either;
26 import org.apache.http.HttpStatus;
27 import org.openecomp.sdc.be.components.distribution.engine.*;
28 import org.openecomp.sdc.be.components.impl.ResponseFormatManager;
29 import org.openecomp.sdc.be.config.BeEcompErrorManager;
30 import org.openecomp.sdc.be.config.ConfigurationManager;
31 import org.openecomp.sdc.be.config.DistributionEngineConfiguration;
32 import org.openecomp.sdc.be.dao.api.ActionStatus;
33 import org.openecomp.sdc.be.distribution.api.client.*;
34 import org.openecomp.sdc.common.datastructure.Wrapper;
35 import org.openecomp.sdc.exception.ResponseFormat;
36 import org.slf4j.Logger;
37 import org.slf4j.LoggerFactory;
38 import org.springframework.stereotype.Component;
39
40 import javax.annotation.Resource;
41 import javax.ws.rs.core.Response;
42 import java.util.List;
43
44 import static org.apache.commons.lang.BooleanUtils.isTrue;
45 import static org.openecomp.sdc.be.components.distribution.engine.DistributionEngineInitTask.buildTopicName;
46 import static org.openecomp.sdc.be.config.ConfigurationManager.getConfigurationManager;
47
48 @Component("distributionBusinessLogic")
49 public class DistributionBusinessLogic {
50     public static final String REGISTER_IN_DISTRIBUTION_ENGINE = "registerInDistributionEngine";
51     public static final String UN_REGISTER_IN_DISTRIBUTION_ENGINE = "unregisterInDistributionEngine";
52     private Gson gson = new GsonBuilder().setPrettyPrinting().create();
53     private static final Logger LOGGER = LoggerFactory.getLogger(DistributionBusinessLogic.class);
54     @Resource
55     private IDistributionEngine distributionEngine;
56
57     private ResponseFormatManager responseFormatManager = ResponseFormatManager.getInstance();
58     private CambriaHandler cambriaHandler;
59
60     private void initRequestEnvEndPoints(RegistrationRequest registrationRequest, DistributionEngineConfiguration config) {
61         if(registrationRequest.getDistEnvEndPoints() == null || registrationRequest.getDistEnvEndPoints().isEmpty()){
62             registrationRequest.setDistEnvEndPoints(config.getUebServers());
63         }
64     }
65     public Either<ServerListResponse, ResponseFormat> getUebServerList() {
66
67         DistributionEngineConfiguration distributionEngineConfiguration = ConfigurationManager.getConfigurationManager()
68                 .getDistributionEngineConfiguration();
69
70         List<String> serverList = distributionEngineConfiguration.getUebServers();
71
72         if (serverList != null && !serverList.isEmpty()) {
73
74             ServerListResponse serverListResponse = new ServerListResponse();
75
76             serverListResponse.setUebServerList(serverList);
77
78             return Either.left(serverListResponse);
79         } else {
80             ResponseFormat errorResponseWrapper = getResponseFormatManager()
81                     .getResponseFormat(ActionStatus.GENERAL_ERROR);
82             return Either.right(errorResponseWrapper);
83         }
84
85     }
86
87     public void handleRegistration(Wrapper<Response> responseWrapper, RegistrationRequest registrationRequest,
88             AuditHandler auditHandler) {
89         CambriaErrorResponse registerResponse = null;
90         try {
91             DistributionEngineConfiguration config = getConfigurationManager().getDistributionEngineConfiguration();
92             String statusTopicName = buildTopicName(config.getDistributionStatusTopicName(),
93                     registrationRequest.getDistrEnvName());
94             registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
95                     SubscriberTypeEnum.PRODUCER, statusTopicName);
96
97             auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.PRODUCER, statusTopicName);
98             boolean isRegisteredAsProducerOnStatusSuccess = responseWrapper.isEmpty();
99
100             // Story [347698] Distribution Client Get Indication from
101             // component whether to register as consumer and producer on
102             // status topic
103             boolean registeredAsConsumerOnStatus = false;
104             if (isRegisteredAsProducerOnStatusSuccess && isTrue(registrationRequest.getIsConsumerToSdcDistrStatusTopic())) {
105                 registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
106                         SubscriberTypeEnum.CONSUMER, statusTopicName);
107                 auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, statusTopicName);
108                 registeredAsConsumerOnStatus = responseWrapper.isEmpty();
109
110             }
111
112             if (responseWrapper.isEmpty()) {
113                 String notificationTopicName = buildTopicName(config.getDistributionNotifTopicName(),
114                         registrationRequest.getDistrEnvName());
115                 registerResponse = registerDistributionClientToTopic(responseWrapper, registrationRequest,
116                         SubscriberTypeEnum.CONSUMER, notificationTopicName);
117                 auditHandler.auditRegisterACL(registerResponse, SubscriberTypeEnum.CONSUMER, notificationTopicName);
118             }
119             // Unregister Rollback
120             if (!responseWrapper.isEmpty()) {
121                 if (isRegisteredAsProducerOnStatusSuccess) {
122                     CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,
123                             SubscriberTypeEnum.PRODUCER, statusTopicName);
124                     auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.PRODUCER, statusTopicName);
125                 }
126                 if (registeredAsConsumerOnStatus) {
127                     CambriaErrorResponse unRegisterResponse = unRegisterDistributionClientFromTopic(registrationRequest,
128                             SubscriberTypeEnum.CONSUMER, statusTopicName);
129                     auditHandler.auditUnRegisterACL(unRegisterResponse, SubscriberTypeEnum.CONSUMER, statusTopicName);
130                 }
131             }
132
133             if (responseWrapper.isEmpty()) {
134                 TopicRegistrationResponse okTopicResponse = buildTopicResponse(registrationRequest);
135                 responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(okTopicResponse).build());
136             }
137
138         } catch (Exception e) {
139             LOGGER.error("registration to topic failed", e);
140             BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,
141                     "registration of subscriber to topic");
142             Response errorResponse = buildErrorResponse(
143                     getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
144             responseWrapper.setInnerElement(errorResponse);
145         } finally {
146             auditHandler.auditRegisterRequest(registerResponse);
147         }
148     }
149
150     public void handleUnRegistration(Wrapper<Response> responseWrapper, RegistrationRequest unRegistrationRequest,
151             AuditHandler auditHandler) {
152         Wrapper<CambriaErrorResponse> cambriaResponseWrapper = new Wrapper<>();
153         try {
154             String statusTopicName = getStatusTopicName(unRegistrationRequest.getDistrEnvName());
155             CambriaErrorResponse unregisterClientProducerTopicResponse = unRegisterDistributionClientFromTopic(
156                     unRegistrationRequest, SubscriberTypeEnum.PRODUCER, statusTopicName);
157             auditHandler.auditUnRegisterACL(unregisterClientProducerTopicResponse, SubscriberTypeEnum.PRODUCER,
158                     statusTopicName);
159             updateResponseWrapper(cambriaResponseWrapper, unregisterClientProducerTopicResponse);
160
161             String notificationTopicName = getNotificationTopicName(unRegistrationRequest.getDistrEnvName());
162             CambriaErrorResponse unregisterClientConsumerTopicResponse = unRegisterDistributionClientFromTopic(
163                     unRegistrationRequest, SubscriberTypeEnum.CONSUMER, notificationTopicName);
164             auditHandler.auditUnRegisterACL(unregisterClientConsumerTopicResponse, SubscriberTypeEnum.CONSUMER,
165                     notificationTopicName);
166             updateResponseWrapper(cambriaResponseWrapper, unregisterClientConsumerTopicResponse);
167
168             // Success unregister both topics
169             TopicUnregistrationResponse unregisterResponse = new TopicUnregistrationResponse(
170                     getNotificationTopicName(unRegistrationRequest.getDistrEnvName()),
171                     getStatusTopicName(unRegistrationRequest.getDistrEnvName()),
172                     unregisterClientConsumerTopicResponse.getOperationStatus(),
173                     unregisterClientProducerTopicResponse.getOperationStatus());
174
175             if (cambriaResponseWrapper.getInnerElement().getOperationStatus() == CambriaOperationStatus.OK) {
176                 responseWrapper.setInnerElement(Response.status(HttpStatus.SC_OK).entity(unregisterResponse).build());
177             } else {
178                 BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(UN_REGISTER_IN_DISTRIBUTION_ENGINE,
179                         "unregistration failed");
180                 responseWrapper.setInnerElement(
181                         Response.status(HttpStatus.SC_INTERNAL_SERVER_ERROR).entity(unregisterResponse).build());
182             }
183         } catch (Exception e) {
184             LOGGER.error("unregistered to topic failed", e);
185             Response errorResponse = buildErrorResponse(
186                     getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
187             responseWrapper.setInnerElement(errorResponse);
188
189         } finally {
190             auditHandler.auditUnRegisterRequest(cambriaResponseWrapper.getInnerElement());
191         }
192     }
193
194     private void updateResponseWrapper(Wrapper<CambriaErrorResponse> cambriaResponseWrapper,
195             CambriaErrorResponse currentResponse) {
196         if (cambriaResponseWrapper.isEmpty()) {
197             cambriaResponseWrapper.setInnerElement(currentResponse);
198         } else if (currentResponse.getOperationStatus() != CambriaOperationStatus.OK) {
199             cambriaResponseWrapper.setInnerElement(currentResponse);
200
201         }
202
203     }
204
205     public static String getNotificationTopicName(String envName) {
206         DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
207                 .getDistributionEngineConfiguration();
208         return DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(), envName);
209
210     }
211
212     public static String getStatusTopicName(String envName) {
213         DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
214                 .getDistributionEngineConfiguration();
215         return DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(), envName);
216
217     }
218
219     protected CambriaErrorResponse unRegisterDistributionClientFromTopic(RegistrationRequest unRegistrationRequest,
220             SubscriberTypeEnum subscriberType, String topicName) {
221         DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
222                 .getDistributionEngineConfiguration();
223         initRequestEnvEndPoints(unRegistrationRequest, config);
224
225         LOGGER.debug("unregistering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, unRegistrationRequest.getDistEnvEndPoints());
226         return getCambriaHandler().unRegisterFromTopic(unRegistrationRequest.getDistEnvEndPoints(), config.getUebPublicKey(),
227                 config.getUebSecretKey(), unRegistrationRequest.getApiPublicKey(), subscriberType, topicName);
228     }
229
230     private TopicRegistrationResponse buildTopicResponse(RegistrationRequest registrationRequest) {
231         DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
232                 .getDistributionEngineConfiguration();
233         String statusTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionStatusTopicName(),
234                 registrationRequest.getDistrEnvName());
235         String notificationTopicName = DistributionEngineInitTask.buildTopicName(config.getDistributionNotifTopicName(),
236                 registrationRequest.getDistrEnvName());
237
238         TopicRegistrationResponse topicResponse = new TopicRegistrationResponse();
239         topicResponse.setDistrNotificationTopicName(notificationTopicName);
240         topicResponse.setDistrStatusTopicName(statusTopicName);
241         return topicResponse;
242     }
243
244     protected CambriaErrorResponse registerDistributionClientToTopic(Wrapper<Response> responseWrapper,
245             RegistrationRequest registrationRequest, SubscriberTypeEnum subscriberType, String topicName) {
246         DistributionEngineConfiguration config = ConfigurationManager.getConfigurationManager()
247                 .getDistributionEngineConfiguration();
248         initRequestEnvEndPoints(registrationRequest, config);
249         String errorMsg;
250
251         // Register for notifications as consumer
252         if (subscriberType == SubscriberTypeEnum.CONSUMER) {
253             errorMsg = "registration of subscriber to topic:" + topicName + " as consumer failed";
254         }
255         // Register for status as producer
256         else {
257             errorMsg = "registration of subscriber to topic:" + topicName + " as producer failed";
258         }
259         LOGGER.debug("registering client as {} , from topic: {}, using DistEnvPoints: {}", subscriberType, topicName, registrationRequest.getDistEnvEndPoints());
260         CambriaErrorResponse registerToTopic = getCambriaHandler().registerToTopic(registrationRequest.getDistEnvEndPoints(),
261                 config.getUebPublicKey(), config.getUebSecretKey(), registrationRequest.getApiPublicKey(),
262                 subscriberType, topicName);
263
264         if (registerToTopic.getOperationStatus() != CambriaOperationStatus.OK) {
265             Response failedRegistrationResponse = buildErrorResponse(
266                     getResponseFormatManager().getResponseFormat(ActionStatus.GENERAL_ERROR));
267             BeEcompErrorManager.getInstance().logBeDistributionEngineSystemError(REGISTER_IN_DISTRIBUTION_ENGINE,
268                     errorMsg);
269             responseWrapper.setInnerElement(failedRegistrationResponse);
270         }
271         return registerToTopic;
272     }
273
274     protected Response buildErrorResponse(ResponseFormat requestErrorWrapper) {
275         return Response.status(requestErrorWrapper.getStatus())
276                 .entity(gson.toJson(requestErrorWrapper.getRequestError())).build();
277     }
278
279     public ResponseFormatManager getResponseFormatManager() {
280         return responseFormatManager;
281     }
282
283     public IDistributionEngine getDistributionEngine() {
284         return distributionEngine;
285     }
286
287     public CambriaHandler getCambriaHandler() {
288         if (cambriaHandler == null) {
289             cambriaHandler = new CambriaHandler();
290         }
291         return cambriaHandler;
292     }
293
294 }