c338e5b90b42472d699104b74a8e2625c85ed60f
[aai/model-loader.git] / src / main / java / org / onap / aai / modelloader / service / ModelLoaderService.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.modelloader.service;
22
23 import java.io.IOException;
24 import java.nio.file.Files;
25 import java.nio.file.Paths;
26 import java.util.ArrayList;
27 import java.util.Base64;
28 import java.util.Date;
29 import java.util.List;
30 import java.util.Properties;
31 import java.util.Timer;
32 import java.util.TimerTask;
33
34 import javax.annotation.PostConstruct;
35 import javax.ws.rs.core.MediaType;
36 import javax.ws.rs.core.Response;
37
38 import org.onap.aai.cl.api.Logger;
39 import org.onap.aai.cl.eelf.LoggerFactory;
40 import org.onap.aai.modelloader.config.ModelLoaderConfig;
41 import org.onap.aai.modelloader.entity.Artifact;
42 import org.onap.aai.modelloader.notification.ArtifactDownloadManager;
43 import org.onap.aai.modelloader.notification.EventCallback;
44 import org.onap.aai.modelloader.notification.NotificationDataImpl;
45 import org.onap.aai.modelloader.notification.NotificationPublisher;
46 import org.onap.sdc.api.IDistributionClient;
47 import org.onap.sdc.api.notification.IArtifactInfo;
48 import org.onap.sdc.api.results.IDistributionClientResult;
49 import org.onap.sdc.impl.DistributionClientFactory;
50 import org.onap.sdc.utils.DistributionActionResultEnum;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.beans.factory.annotation.Value;
53 import org.springframework.web.bind.annotation.PathVariable;
54 import org.springframework.web.bind.annotation.RequestBody;
55 import org.springframework.web.bind.annotation.RequestMapping;
56 import org.springframework.web.bind.annotation.RestController;
57
58 /**
59  * Service class in charge of managing the negotiating model loading capabilities between AAI and an ASDC.
60  */
61 @RestController
62 @RequestMapping("/services/model-loader/v1/model-service")
63 public class ModelLoaderService implements ModelLoaderInterface {
64
65     private static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
66
67     @Value("${CONFIG_HOME}")
68     private String configDir;
69     private IDistributionClient client;
70     private ModelLoaderConfig config;
71     @Autowired
72     private BabelServiceClientFactory babelClientFactory;
73
74     /**
75      * Responsible for loading configuration files and calling initialization.
76      */
77     @PostConstruct
78     protected void start() {
79         // Load model loader system configuration
80         logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
81         ModelLoaderConfig.setConfigHome(configDir);
82         Properties configProperties = new Properties();
83         try {
84             configProperties.load(Files.newInputStream(Paths.get(configDir, "model-loader.properties")));
85             config = new ModelLoaderConfig(configProperties);
86             
87             // Set the truststore for SDC Client to connect to Dmaap central bus if applicable (as in case of TI)
88             if (config.isUseHttpsWithDmaap()) {
89                 String trustStorePath = config.getKeyStorePath();
90                 String trustStorePassword = config.getKeyStorePassword();
91                 if (trustStorePath != null && Paths.get(trustStorePath).toFile().isFile() && trustStorePassword != null
92                         && !trustStorePassword.isEmpty()) {
93                     System.setProperty("javax.net.ssl.trustStore", trustStorePath);
94                     System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword);
95                 } else {
96                     throw new IllegalArgumentException("Model Loader property ml.distribution.KEYSTORE_FILE "
97                                 + "or ml.distribution.KEYSTORE_PASSWORD not set or invalid");
98                 }
99             }
100             
101             if (!config.getASDCConnectionDisabled()) {
102                 initSdcClient();
103             }
104         } catch (IOException e) {
105             String errorMsg = "Failed to load configuration: " + e.getMessage();
106             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
107         }
108     }
109
110     /**
111      * Responsible for stopping the connection to the distribution client before the resource is destroyed.
112      */
113     public void preShutdownOperations() {
114         logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
115         if (client != null) {
116             client.stop();
117         }
118     }
119
120     /**
121      * Responsible for loading configuration files, initializing model distribution clients, and starting them.
122      */
123     protected void initSdcClient() {
124         // Initialize distribution client
125         logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
126         client = DistributionClientFactory.createDistributionClient();
127         EventCallback callback = new EventCallback(client, config, babelClientFactory);
128
129         IDistributionClientResult initResult = client.init(config, callback);
130
131         if (initResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
132             // Start distribution client
133             logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
134             IDistributionClientResult startResult = client.start();
135             if (startResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
136                 logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
137             } else {
138                 String errorMsg = "Failed to start distribution client: " + startResult.getDistributionMessageResult();
139                 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
140
141                 // Kick off a timer to retry the SDC connection
142                 Timer timer = new Timer();
143                 TimerTask task = new SdcConnectionJob(client, config, callback, timer);
144                 timer.schedule(task, new Date(), 60000);
145             }
146         } else {
147             String errorMsg = "Failed to initialize distribution client: " + initResult.getDistributionMessageResult();
148             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
149
150             // Kick off a timer to retry the SDC connection
151             Timer timer = new Timer();
152             TimerTask task = new SdcConnectionJob(client, config, callback, timer);
153             timer.schedule(task, new Date(), 60000);
154         }
155
156         Runtime.getRuntime().addShutdownHook(new Thread(this::preShutdownOperations));
157     }
158
159     /**
160      * (non-Javadoc)
161      *
162      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
163      */
164     @Override
165     public Response loadModel(@PathVariable String modelid) {
166         return Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
167     }
168
169     /**
170      * (non-Javadoc)
171      *
172      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
173      */
174     @Override
175     public Response saveModel(@PathVariable String modelid, @PathVariable String modelname) {
176         return Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}").build();
177     }
178
179     @Override
180     public Response ingestModel(@PathVariable String modelName, @PathVariable String modelVersion,
181             @RequestBody String payload) throws IOException {
182         Response response;
183
184         if (config.getIngestSimulatorEnabled()) {
185             response = processTestArtifact(modelName, modelVersion, payload);
186         } else {
187             logger.debug("Simulation interface disabled");
188             response = Response.serverError().build();
189         }
190
191         return response;
192     }
193
194     private Response processTestArtifact(String modelName, String modelVersion, String payload) {
195         IArtifactInfo artifactInfo = new ArtifactInfoImpl();
196         ((ArtifactInfoImpl) artifactInfo).setArtifactName(modelName);
197         ((ArtifactInfoImpl) artifactInfo).setArtifactVersion(modelVersion);
198
199         Response response;
200         try {
201             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact " + modelName + " " + modelVersion);
202
203             byte[] csarFile = Base64.getDecoder().decode(payload);
204
205             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Generating XML models from test artifact");
206
207             List<Artifact> modelArtifacts = new ArrayList<>();
208             List<Artifact> catalogArtifacts = new ArrayList<>();
209
210             new ArtifactDownloadManager(client, config, babelClientFactory).processToscaArtifacts(modelArtifacts,
211                     catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
212
213             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifacts: "
214                     + modelArtifacts.size() + " model(s) and " + catalogArtifacts.size() + " catalog(s)");
215
216             NotificationDataImpl notificationData = new NotificationDataImpl();
217             notificationData.setDistributionID("TestDistributionID");
218             boolean success =
219                     new ArtifactDeploymentManager(config).deploy(notificationData, modelArtifacts, catalogArtifacts);
220             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Deployment success was " + success);
221             response = success ? Response.ok().build() : Response.serverError().build();
222         } catch (Exception e) {
223             String responseMessage = e.getMessage();
224             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Exception handled: " + responseMessage);
225             if (config.getASDCConnectionDisabled()) {
226                 // Make sure the NotificationPublisher logger is invoked as per the standard processing flow.
227                 new NotificationPublisher().publishDeployFailure(client, new NotificationDataImpl(), artifactInfo);
228             } else {
229                 responseMessage += "\nSDC publishing is enabled but has been bypassed";
230             }
231             response = Response.serverError().entity(responseMessage).type(MediaType.APPLICATION_XML).build();
232         }
233         return response;
234     }
235 }