2 * ============LICENSE_START=======================================================
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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.onap.aai.modelloader.service;
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;
35 import javax.annotation.PostConstruct;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
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;
60 * Service class in charge of managing the negotiating model loading capabilities between AAI and an ASDC.
63 @RequestMapping("/services/model-loader/v1/model-service")
64 public class ModelLoaderService implements ModelLoaderInterface {
66 private static final Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
68 @Value("${CONFIG_HOME}")
69 private String configDir;
70 private IDistributionClient client;
71 private ModelLoaderConfig config;
73 private BabelServiceClientFactory babelClientFactory;
76 * Responsible for loading configuration files and calling initialization.
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()) {
90 } catch (IOException e) {
91 String errorMsg = "Failed to load configuration: " + e.getMessage();
92 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
97 * Responsible for stopping the connection to the distribution client before the resource is destroyed.
99 public void preShutdownOperations() {
100 logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
101 if (client != null) {
107 * Responsible for loading configuration files, initializing model distribution clients, and starting them.
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);
115 IDistributionClientResult initResult = client.init(config, callback);
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");
124 String errorMsg = "Failed to start distribution client: " + startResult.getDistributionMessageResult();
125 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
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);
133 String errorMsg = "Failed to initialize distribution client: " + initResult.getDistributionMessageResult();
134 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
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);
142 Runtime.getRuntime().addShutdownHook(new Thread(this::preShutdownOperations));
148 * @see org.onap.aai.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
151 public Response loadModel(@PathVariable String modelid) {
152 return Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
158 * @see org.onap.aai.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
161 public Response saveModel(@PathVariable String modelid, @PathVariable String modelname) {
162 return Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}").build();
166 public Response ingestModel(@PathVariable String modelName, @PathVariable String modelVersion,
167 @RequestBody String payload) throws IOException {
170 if (config.getIngestSimulatorEnabled()) {
171 response = processTestArtifact(modelName, modelVersion, payload);
173 logger.debug("Simulation interface disabled");
174 response = Response.serverError().build();
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);
187 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact " + modelName + " " + modelVersion);
189 byte[] csarFile = Base64.getDecoder().decode(payload);
191 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Generating XML models from test artifact");
193 List<Artifact> modelArtifacts = new ArrayList<>();
194 List<Artifact> catalogArtifacts = new ArrayList<>();
196 new ArtifactDownloadManager(client, config, babelClientFactory).processToscaArtifacts(modelArtifacts,
197 catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
199 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifacts: "
200 + modelArtifacts.size() + " model(s) and " + catalogArtifacts.size() + " catalog(s)");
202 NotificationDataImpl notificationData = new NotificationDataImpl();
203 notificationData.setDistributionID("TestDistributionID");
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);
215 responseMessage += "\nSDC publishing is enabled but has been bypassed";
217 response = Response.serverError().entity(responseMessage).type(MediaType.APPLICATION_XML).build();