Adding sync mechanism
[so.git] / adapters / mso-vnfm-adapter / mso-vnfm-etsi-adapter / src / main / java / org / onap / so / adapters / vnfmadapter / packagemanagement / subscriptionmanagement / SubscriptionManager.java
1 /*-
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2020 Nordix Foundation.
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.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement;
22
23 import static org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.SubscriptionAuthentication.AuthTypeEnum.BASIC;
24 import static org.slf4j.LoggerFactory.getLogger;
25 import java.net.URI;
26 import java.security.GeneralSecurityException;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Objects;
31 import java.util.Optional;
32 import org.onap.so.adapters.vnfmadapter.Constants;
33 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProvider;
34 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.BasicAuth;
35 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription;
36 import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription;
37 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2002;
38 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.PkgmSubscriptionRequest;
39 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.SubscriptionsLinks;
40 import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesLinksSelf;
41 import org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement.cache.PackageManagementCacheServiceProvider;
42 import org.onap.so.adapters.vnfmadapter.rest.exceptions.InternalServerErrorException;
43 import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionNotFoundException;
44 import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionRequestConversionException;
45 import org.onap.so.utils.CryptoUtils;
46 import org.slf4j.Logger;
47 import org.springframework.beans.factory.annotation.Autowired;
48 import org.springframework.beans.factory.annotation.Value;
49 import org.springframework.core.convert.ConversionException;
50 import org.springframework.core.convert.ConversionService;
51 import org.springframework.stereotype.Service;
52
53 /**
54  * Manages package management subscriptions from the VNFMs
55  *
56  * @author Ronan Kenny (ronan.kenny@est.tech)
57  * @author Gareth Roper (gareth.roper@est.tech)
58  */
59 @Service
60 public class SubscriptionManager {
61
62     private static final Logger logger = getLogger(SubscriptionManager.class);
63     private final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider;
64     private final ConversionService conversionService;
65     private final EtsiCatalogServiceProvider etsiCatalogServiceProvider;
66     private final String vnfmAdapterEndpoint;
67     private final String msoKeyString;
68     private final String vnfmAdapterAuth;
69
70
71     @Autowired
72     public SubscriptionManager(final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider,
73             final ConversionService conversionService, final EtsiCatalogServiceProvider etsiCatalogServiceProvider,
74             @Value("${vnfmadapter.endpoint}") final String vnfmAdapterEndpoint,
75             @Value("${mso.key}") final String msoKeyString,
76             @Value("${vnfmadapter.auth:BF29BA36F0CFE1C05507781F6B97EFBCA7EFAC9F595954D465FC43F646883EF585C20A58CBB02528A6FAAC}") final String vnfmAdapterAuth) {
77         this.packageManagementCacheServiceProvider = packageManagementCacheServiceProvider;
78         this.conversionService = conversionService;
79         this.etsiCatalogServiceProvider = etsiCatalogServiceProvider;
80         this.vnfmAdapterEndpoint = vnfmAdapterEndpoint;
81         this.vnfmAdapterAuth = vnfmAdapterAuth;
82         this.msoKeyString = msoKeyString;
83     }
84
85     public Optional<InlineResponse2002> createSubscription(final PkgmSubscriptionRequest pkgmSubscriptionRequest)
86             throws GeneralSecurityException {
87
88         final org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest =
89                 buildEtsiCatalogManagerPkgmSubscriptionRequest(pkgmSubscriptionRequest);
90
91         final Optional<PkgmSubscription> optionalEtsiCatalogManagerSubscription =
92                 etsiCatalogServiceProvider.postSubscription(etsiCatalogManagerSubscriptionRequest);
93
94         if (optionalEtsiCatalogManagerSubscription.isPresent()) {
95             final PkgmSubscription etsiCatalogManagerSubscription = optionalEtsiCatalogManagerSubscription.get();
96             logger.debug("postPkgmSubscriptionRequest Response SubscriptionId: {}",
97                     Objects.requireNonNull(etsiCatalogManagerSubscription.getId()));
98             final String subscriptionId = etsiCatalogManagerSubscription.getId();
99
100             packageManagementCacheServiceProvider.addSubscription(subscriptionId, pkgmSubscriptionRequest);
101
102             final InlineResponse2002 response2002 = new InlineResponse2002();
103             response2002.setId(subscriptionId);
104             response2002.setFilter(pkgmSubscriptionRequest.getFilter());
105             response2002.setCallbackUri(getSubscriptionUri(subscriptionId).toString());
106             response2002.setLinks(new SubscriptionsLinks()
107                     .self(new VnfPackagesLinksSelf().href(getSubscriptionUri(subscriptionId).toString())));
108
109             return Optional.of(response2002);
110         }
111         throw new InternalServerErrorException(
112                 "Received empty response from POST to ETSI Catalog Manager Subscription Endpoint.");
113     }
114
115
116     public Optional<String> getSubscriptionId(final PkgmSubscriptionRequest pkgmSubscriptionRequest) {
117         return packageManagementCacheServiceProvider.getSubscriptionId(pkgmSubscriptionRequest);
118     }
119
120     public Optional<InlineResponse2002> getSubscription(final String subscriptionId) {
121
122         logger.debug("Checking if subscrition with id: {} exists in ETSI Catalog Manager", subscriptionId);
123         final Optional<NsdmSubscription> etsiCatalogSubscriptionOption =
124                 etsiCatalogServiceProvider.getSubscription(subscriptionId);
125
126         if (!etsiCatalogSubscriptionOption.isPresent()) {
127             logger.debug("Unable to find subscription in ETSI Catalog Manager using id: {}", subscriptionId);
128             if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) {
129                 logger.debug("will remove subcription with id: {} from local cache", subscriptionId);
130                 packageManagementCacheServiceProvider.deleteSubscription(subscriptionId);
131             }
132         }
133
134         final Optional<PkgmSubscriptionRequest> optional =
135                 packageManagementCacheServiceProvider.getSubscription(subscriptionId);
136         if (optional.isPresent()) {
137             final PkgmSubscriptionRequest subscription = optional.get();
138             return Optional.of(getInlineResponse2002(subscriptionId, subscription));
139         }
140         return Optional.empty();
141     }
142
143     public List<InlineResponse2002> getSubscriptions() {
144         final Map<String, PkgmSubscriptionRequest> subscriptions =
145                 packageManagementCacheServiceProvider.getSubscriptions();
146         final List<InlineResponse2002> response = new ArrayList<>();
147         subscriptions.forEach((key, value) -> {
148             final Optional<InlineResponse2002> optional = getSubscription(key);
149             if (optional.isPresent()) {
150                 response.add(optional.get());
151             }
152         });
153         return response;
154     }
155
156     public boolean deleteSubscription(final String subscriptionId) {
157         if (packageManagementCacheServiceProvider.getSubscription(subscriptionId).isPresent()) {
158             try {
159                 if (etsiCatalogServiceProvider.deleteSubscription(subscriptionId)) {
160                     return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId);
161                 }
162             } catch (final SubscriptionNotFoundException subscriptionNotFoundException) {
163                 logger.error(
164                         "Unable to find subscription in ETSI Catalog Manager using id: {} will delete it from local cache",
165                         subscriptionId);
166                 return packageManagementCacheServiceProvider.deleteSubscription(subscriptionId);
167             }
168         }
169         return false;
170     }
171
172     public URI getSubscriptionUri(final String subscriptionId) {
173         return URI.create(
174                 vnfmAdapterEndpoint + Constants.PACKAGE_MANAGEMENT_BASE_URL + "/subscriptions/" + subscriptionId);
175     }
176
177     private InlineResponse2002 getInlineResponse2002(final String id, final PkgmSubscriptionRequest subscription) {
178         return new InlineResponse2002().id(id).filter(subscription.getFilter())
179                 .callbackUri(subscription.getCallbackUri());
180     }
181
182     private org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest buildEtsiCatalogManagerPkgmSubscriptionRequest(
183             final PkgmSubscriptionRequest pkgmSubscriptionRequest) throws GeneralSecurityException {
184
185         final org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest;
186         try {
187             etsiCatalogManagerSubscriptionRequest = conversionService.convert(pkgmSubscriptionRequest,
188                     org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest.class);
189         } catch (final ConversionException conversionException) {
190             logger.error(conversionException.getMessage());
191             throw new SubscriptionRequestConversionException(
192                     "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest");
193         } catch (final Exception exception) {
194             logger.error(exception.getMessage());
195             throw new InternalServerErrorException(
196                     "Could not convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest");
197         }
198
199         if (etsiCatalogManagerSubscriptionRequest != null) {
200             etsiCatalogManagerSubscriptionRequest
201                     .setCallbackUri(vnfmAdapterEndpoint + Constants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL);
202
203             final String[] auth = decryptAuth();
204             final String username = auth[0];
205             final String password = auth[1];
206
207             etsiCatalogManagerSubscriptionRequest.setAuthentication(
208                     new org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.SubscriptionAuthentication()
209                             .addAuthTypeItem(BASIC).paramsBasic(new BasicAuth().userName(username).password(password)));
210             return etsiCatalogManagerSubscriptionRequest;
211         }
212         throw new SubscriptionRequestConversionException(
213                 "Failed to convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest");
214     }
215
216     private String[] decryptAuth() throws GeneralSecurityException {
217         final String decryptedAuth = CryptoUtils.decrypt(vnfmAdapterAuth, msoKeyString);
218         final String[] auth = decryptedAuth.split(":");
219         return auth;
220     }
221
222 }