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