Fix container startup
[vfc/nfvo/driver/vnfm/svnfm.git] / nokiav2 / driver / src / main / java / org / onap / vfc / nfvo / driver / vnfm / svnfm / nokia / onap / core / SelfRegistrationManager.java
1 /*
2  * Copyright 2016-2017, Nokia Corporation
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.onap.core;
18
19 import com.nokia.cbam.lcn.v32.api.SubscriptionsApi;
20 import com.nokia.cbam.lcn.v32.model.*;
21 import java.util.ArrayList;
22 import org.onap.msb.model.MicroServiceFullInfo;
23 import org.onap.msb.model.MicroServiceInfo;
24 import org.onap.msb.model.Node;
25 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider;
26 import org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.DriverProperties;
27 import org.slf4j.Logger;
28 import org.springframework.beans.factory.annotation.Autowired;
29 import org.springframework.beans.factory.annotation.Value;
30 import org.springframework.stereotype.Component;
31
32 import static com.nokia.cbam.lcn.v32.model.SubscriptionAuthentication.TypeEnum.NONE;
33 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.CbamUtils.buildFatalFailure;
34 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.util.SystemFunctions.systemFunctions;
35 import static org.onap.vfc.nfvo.driver.vnfm.svnfm.nokia.vnfm.CbamRestApiProvider.NOKIA_LCN_API_VERSION;
36 import static org.slf4j.LoggerFactory.getLogger;
37
38 /**
39  * Responsible for registering the driver in the core systems.
40  */
41 @Component
42 public class SelfRegistrationManager {
43     public static final String DRIVER_VERSION = "v1";
44     public static final String SERVICE_NAME = "NokiaSVNFM";
45     public static final String SWAGGER_API_DEFINITION = "self.swagger.json";
46     private static Logger logger = getLogger(SelfRegistrationManager.class);
47     private final DriverProperties driverProperties;
48     private final MsbApiProvider msbApiProvider;
49     private final CbamRestApiProvider cbamRestApiProvider;
50     @Value("${driverMsbExternalIp}")
51     private String driverMsbExternalIp;
52     @Value("${driverVnfmExternalIp}")
53     private String driverVnfmExternalIp;
54     @Value("${server.port}")
55     private String driverPort;
56     private volatile boolean ready = false;
57
58     @Autowired
59     SelfRegistrationManager(DriverProperties driverProperties, MsbApiProvider msbApiProvider, CbamRestApiProvider cbamRestApiProvider) {
60         this.cbamRestApiProvider = cbamRestApiProvider;
61         this.msbApiProvider = msbApiProvider;
62         this.driverProperties = driverProperties;
63     }
64
65     /**
66      * Register the driver in micro-service bus and subscribe to LCNs from CBAM
67      */
68     public void register() {
69         //the order is important (only publish it's existence after the subscription has been created)
70         subscribeToLcn(driverProperties.getVnfmId());
71         try {
72             registerMicroService();
73         } catch (RuntimeException e) {
74             deleteSubscription(driverProperties.getVnfmId());
75             throw e;
76         }
77         ready = true;
78     }
79
80     /**
81      * De-register the VNFM driver from the micro-service bus
82      */
83     public void deRegister() {
84         try {
85             logger.info("Cancelling micro service registration");
86             msbApiProvider.getMsbApi().deleteMicroService(SERVICE_NAME, DRIVER_VERSION, null, null).blockingFirst();
87         } catch (Exception e) {
88             //ONAP throws 500 internal server error, but deletes the micro service
89             boolean serviceFoundAfterDelete = false;
90             try {
91                 msbApiProvider.getMsbApi().getMicroService_0(SERVICE_NAME, DRIVER_VERSION, null, null, null, null, null);
92                 serviceFoundAfterDelete = true;
93             } catch (Exception e1) {
94                 logger.info("Unable to query " + SERVICE_NAME + " from MSB (so the service was successfully deleted)", e1);
95                 // the micro service was deleted (even though 500 HTTP code was reported)
96             }
97             if (serviceFoundAfterDelete) {
98                 throw buildFatalFailure(logger, "Unable to deRegister Nokia VNFM driver", e);
99             }
100         }
101         deleteSubscription(driverProperties.getVnfmId());
102     }
103
104     /**
105      * @return the swagger API definition
106      */
107     public byte[] getSwaggerApiDefinition() {
108         return systemFunctions().loadFile(SWAGGER_API_DEFINITION);
109     }
110
111     private String getDriverVnfmUrl() {
112         return "http://" + driverVnfmExternalIp + ":" + driverPort + DriverProperties.BASE_URL;
113     }
114
115     private void deleteSubscription(String vnfmId) {
116         logger.info("Deleting CBAM LCN subscription");
117         SubscriptionsApi lcnApi = cbamRestApiProvider.getCbamLcnApi(vnfmId);
118         try {
119             String callbackUrl = getDriverVnfmUrl() + DriverProperties.LCN_URL;
120             for (Subscription subscription : lcnApi.subscriptionsGet(NOKIA_LCN_API_VERSION).blockingFirst()) {
121                 if (subscription.getCallbackUrl().equals(callbackUrl)) {
122                     logger.info("Deleting subscription with {} identifier", subscription.getId());
123                     lcnApi.subscriptionsSubscriptionIdDelete(subscription.getId(), NOKIA_LCN_API_VERSION).blockingFirst();
124                 }
125             }
126         } catch (Exception e) {
127             throw buildFatalFailure(logger, "Unable to delete CBAM LCN subscription", e);
128         }
129     }
130
131     private MicroServiceFullInfo registerMicroService() {
132         logger.info("Registering micro service");
133         MicroServiceInfo microServiceInfo = new MicroServiceInfo();
134         microServiceInfo.setUrl(DriverProperties.BASE_URL);
135         //the PATH should not be set
136         microServiceInfo.setProtocol(MicroServiceInfo.ProtocolEnum.REST);
137         microServiceInfo.setVisualRange(MicroServiceInfo.VisualRangeEnum._1);
138         microServiceInfo.setServiceName(SERVICE_NAME);
139         microServiceInfo.setVersion(DRIVER_VERSION);
140         microServiceInfo.setEnableSsl(false);
141         Node node = new Node();
142         microServiceInfo.setNodes(new ArrayList<>());
143         microServiceInfo.getNodes().add(node);
144         node.setIp(driverMsbExternalIp);
145         node.setPort(driverPort);
146         node.setTtl("0");
147         try {
148             return msbApiProvider.getMsbApi().addMicroService(microServiceInfo, true, false).blockingFirst();
149         } catch (Exception e) {
150             throw buildFatalFailure(logger, "Unable to register Nokia VNFM driver", e);
151         }
152     }
153
154     private void subscribeToLcn(String vnfmId) {
155         String callbackUrl = getDriverVnfmUrl() + DriverProperties.LCN_URL;
156         logger.info("Subscribing to CBAM LCN {} with callback to {}", driverProperties.getCbamLcnUrl(), callbackUrl);
157         SubscriptionsApi lcnApi = cbamRestApiProvider.getCbamLcnApi(vnfmId);
158         try {
159             for (Subscription subscription : lcnApi.subscriptionsGet(NOKIA_LCN_API_VERSION).blockingFirst()) {
160                 if (subscription.getCallbackUrl().equals(callbackUrl)) {
161                     logger.warn("The subscription with {} identifier has the same callback URL", subscription.getId());
162                     return;
163                 }
164             }
165             CreateSubscriptionRequest request = new CreateSubscriptionRequest();
166             request.setFilter(new SubscriptionFilter());
167             request.getFilter().setNotificationTypes(new ArrayList<>());
168             request.getFilter().getNotificationTypes().add(VnfNotificationType.VNFLIFECYCLECHANGENOTIFICATION);
169             request.setCallbackUrl(callbackUrl);
170             request.getFilter().addOperationTypesItem(OperationType.HEAL);
171             request.getFilter().addOperationTypesItem(OperationType.INSTANTIATE);
172             request.getFilter().addOperationTypesItem(OperationType.SCALE);
173             request.getFilter().addOperationTypesItem(OperationType.TERMINATE);
174             SubscriptionAuthentication subscriptionAuthentication = new SubscriptionAuthentication();
175             subscriptionAuthentication.setType(NONE);
176             request.setAuthentication(subscriptionAuthentication);
177             Subscription createdSubscription = lcnApi.subscriptionsPost(request, NOKIA_LCN_API_VERSION).blockingFirst();
178             logger.info("Subscribed to LCN with {} identifier", createdSubscription.getId());
179         } catch (Exception e) {
180             throw buildFatalFailure(logger, "Unable to subscribe to CBAM LCN", e);
181         }
182     }
183
184     /**
185      * @return is the component ready to serve requests
186      */
187     public boolean isReady() {
188         return ready;
189     }
190 }