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