[SDC-DIST] Upgrade sdc-distro-client to v 2.0.0
[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.io.InputStream;
25 import java.nio.file.Files;
26 import java.nio.file.Paths;
27 import java.util.ArrayList;
28 import java.util.Base64;
29 import java.util.Date;
30 import java.util.List;
31 import java.util.Properties;
32 import java.util.Timer;
33 import java.util.TimerTask;
34
35 import javax.annotation.PostConstruct;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
38
39 import org.onap.aai.cl.api.Logger;
40 import org.onap.aai.cl.eelf.LoggerFactory;
41 import org.onap.aai.modelloader.config.ModelLoaderConfig;
42 import org.onap.aai.modelloader.entity.Artifact;
43 import org.onap.aai.modelloader.notification.ArtifactDownloadManager;
44 import org.onap.aai.modelloader.notification.EventCallback;
45 import org.onap.aai.modelloader.notification.NotificationDataImpl;
46 import org.onap.aai.modelloader.notification.NotificationPublisher;
47 import org.onap.sdc.api.IDistributionClient;
48 import org.onap.sdc.api.notification.IArtifactInfo;
49 import org.onap.sdc.api.results.IDistributionClientResult;
50 import org.onap.sdc.impl.DistributionClientFactory;
51 import org.onap.sdc.utils.DistributionActionResultEnum;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.beans.factory.annotation.Value;
54 import org.springframework.web.bind.annotation.PathVariable;
55 import org.springframework.web.bind.annotation.RequestBody;
56 import org.springframework.web.bind.annotation.RequestMapping;
57 import org.springframework.web.bind.annotation.RestController;
58
59 /**
60  * Service class in charge of managing the negotiating model loading capabilities between AAI and an ASDC.
61  */
62 @RestController
63 @RequestMapping("/services/model-loader/v1/model-service")
64 public class ModelLoaderService implements ModelLoaderInterface {
65
66     private static final Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
67
68     @Value("${CONFIG_HOME}")
69     private String configDir;
70     private IDistributionClient client;
71     private ModelLoaderConfig config;
72     @Autowired
73     private BabelServiceClientFactory babelClientFactory;
74
75     /**
76      * Responsible for loading configuration files and calling initialization.
77      */
78     @PostConstruct
79     protected void start() {
80         // Load model loader system configuration
81         logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
82         ModelLoaderConfig.setConfigHome(configDir);
83         Properties configProperties = new Properties();
84         try (InputStream configInputStream = Files.newInputStream(Paths.get(configDir, "model-loader.properties"))) {
85             configProperties.load(configInputStream);
86             config = new ModelLoaderConfig(configProperties);
87             if (!config.getASDCConnectionDisabled()) {
88                 initSdcClient();
89             }
90         } catch (IOException e) {
91             String errorMsg = "Failed to load configuration: " + e.getMessage();
92             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
93         }
94     }
95
96     /**
97      * Responsible for stopping the connection to the distribution client before the resource is destroyed.
98      */
99     public void preShutdownOperations() {
100         logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
101         if (client != null) {
102             client.stop();
103         }
104     }
105
106     /**
107      * Responsible for loading configuration files, initializing model distribution clients, and starting them.
108      */
109     protected void initSdcClient() {
110         // Initialize distribution client
111         logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
112         client = DistributionClientFactory.createDistributionClient();
113         EventCallback callback = new EventCallback(client, config, babelClientFactory);
114
115         IDistributionClientResult initResult = client.init(config, callback);
116
117         if (initResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
118             // Start distribution client
119             logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
120             IDistributionClientResult startResult = client.start();
121             if (startResult.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
122                 logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
123             } else {
124                 String errorMsg = "Failed to start distribution client: " + startResult.getDistributionMessageResult();
125                 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
126
127                 // Kick off a timer to retry the SDC connection
128                 Timer timer = new Timer();
129                 TimerTask task = new SdcConnectionJob(client, config, callback, timer);
130                 timer.schedule(task, new Date(), 60000);
131             }
132         } else {
133             String errorMsg = "Failed to initialize distribution client: " + initResult.getDistributionMessageResult();
134             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
135
136             // Kick off a timer to retry the SDC connection
137             Timer timer = new Timer();
138             TimerTask task = new SdcConnectionJob(client, config, callback, timer);
139             timer.schedule(task, new Date(), 60000);
140         }
141
142         Runtime.getRuntime().addShutdownHook(new Thread(this::preShutdownOperations));
143     }
144
145     /**
146      * (non-Javadoc)
147      *
148      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
149      */
150     @Override
151     public Response loadModel(@PathVariable String modelid) {
152         return Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
153     }
154
155     /**
156      * (non-Javadoc)
157      *
158      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
159      */
160     @Override
161     public Response saveModel(@PathVariable String modelid, @PathVariable String modelname) {
162         return Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}").build();
163     }
164
165     @Override
166     public Response ingestModel(@PathVariable String modelName, @PathVariable String modelVersion,
167             @RequestBody String payload) throws IOException {
168         Response response;
169
170         if (config.getIngestSimulatorEnabled()) {
171             response = processTestArtifact(modelName, modelVersion, payload);
172         } else {
173             logger.debug("Simulation interface disabled");
174             response = Response.serverError().build();
175         }
176
177         return response;
178     }
179
180     private Response processTestArtifact(String modelName, String modelVersion, String payload) {
181         IArtifactInfo artifactInfo = new ArtifactInfoImpl();
182         ((ArtifactInfoImpl) artifactInfo).setArtifactName(modelName);
183         ((ArtifactInfoImpl) artifactInfo).setArtifactVersion(modelVersion);
184
185         Response response;
186         try {
187             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact " + modelName + " " + modelVersion);
188
189             byte[] csarFile = Base64.getDecoder().decode(payload);
190
191             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Generating XML models from test artifact");
192
193             List<Artifact> modelArtifacts = new ArrayList<>();
194             List<Artifact> catalogArtifacts = new ArrayList<>();
195
196             new ArtifactDownloadManager(client, config, babelClientFactory).processToscaArtifacts(modelArtifacts,
197                     catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
198
199             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifacts: "
200                     + modelArtifacts.size() + " model(s) and " + catalogArtifacts.size() + " catalog(s)");
201
202             NotificationDataImpl notificationData = new NotificationDataImpl();
203             notificationData.setDistributionID("TestDistributionID");
204             boolean success =
205                     new ArtifactDeploymentManager(config).deploy(notificationData, modelArtifacts, catalogArtifacts);
206             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Deployment success was " + success);
207             response = success ? Response.ok().build() : Response.serverError().build();
208         } catch (Exception e) {
209             String responseMessage = e.getMessage();
210             logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Exception handled: " + responseMessage);
211             if (config.getASDCConnectionDisabled()) {
212                 // Make sure the NotificationPublisher logger is invoked as per the standard processing flow.
213                 new NotificationPublisher().publishDeployFailure(client, new NotificationDataImpl(), artifactInfo);
214             } else {
215                 responseMessage += "\nSDC publishing is enabled but has been bypassed";
216             }
217             response = Response.serverError().entity(responseMessage).type(MediaType.APPLICATION_XML).build();
218         }
219         return response;
220     }
221 }