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