a4cc5d1f60d3225223cf9e2bdd72392427f60aa7
[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 Amdocs
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.FileInputStream;
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Base64;
27 import java.util.Date;
28 import java.util.List;
29 import java.util.Properties;
30 import java.util.Timer;
31 import java.util.TimerTask;
32
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.ArtifactDeploymentManager;
40 import org.onap.aai.modelloader.notification.ArtifactDownloadManager;
41 import org.onap.aai.modelloader.notification.EventCallback;
42 import org.onap.aai.modelloader.restclient.BabelServiceClientFactory;
43 import org.openecomp.sdc.api.IDistributionClient;
44 import org.openecomp.sdc.api.notification.IArtifactInfo;
45 import org.openecomp.sdc.api.notification.INotificationData;
46 import org.openecomp.sdc.api.results.IDistributionClientResult;
47 import org.openecomp.sdc.impl.DistributionClientFactory;
48 import org.openecomp.sdc.utils.DistributionActionResultEnum;
49
50 /**
51  * Service class in charge of managing the negotiating model loading capabilities between AAI and an ASDC.
52  */
53 public class ModelLoaderService implements ModelLoaderInterface {
54
55     protected static final String FILESEP =
56             (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
57
58     protected static final String CONFIG_DIR = System.getProperty("CONFIG_HOME") + FILESEP;
59     protected static final String CONFIG_AUTH_LOCATION = CONFIG_DIR + "auth" + FILESEP;
60     protected static final String CONFIG_FILE = CONFIG_DIR + "model-loader.properties";
61
62     private IDistributionClient client;
63     private ModelLoaderConfig config;
64
65     static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
66
67     /**
68      * Responsible for loading configuration files and calling initialization.
69      */
70     public ModelLoaderService() {
71         start();
72     }
73
74     protected void start() {
75         // Load model loader system configuration
76         logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
77         Properties configProperties = new Properties();
78         try {
79             configProperties.load(new FileInputStream(CONFIG_FILE));
80         } catch (IOException e) {
81             String errorMsg = "Failed to load configuration: " + e.getMessage();
82             logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
83             shutdown();
84         }
85
86         config = new ModelLoaderConfig(configProperties, CONFIG_AUTH_LOCATION);
87         init();
88
89         Runtime.getRuntime().addShutdownHook(new Thread(this::preShutdownOperations));
90     }
91
92     /**
93      * Responsible for stopping the connection to the distribution client before the resource is destroyed.
94      */
95     protected void preShutdownOperations() {
96         logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
97         if (client != null) {
98             client.stop();
99         }
100     }
101
102     /**
103      * Responsible for loading configuration files, initializing model distribution clients, and starting them.
104      */
105     protected void init() {
106         if (!config.getASDCConnectionDisabled()) {
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                 String errorMsg =
116                         "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, callback, timer);
122                 timer.schedule(task, new Date(), 60000);
123             } else {
124                 // Start distribution client
125                 logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
126                 IDistributionClientResult startResult = client.start();
127                 if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
128                     String errorMsg =
129                             "Failed to start distribution client: " + startResult.getDistributionMessageResult();
130                     logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
131
132                     // Kick off a timer to retry the SDC connection
133                     Timer timer = new Timer();
134                     TimerTask task = new SdcConnectionJob(client, config, callback, timer);
135                     timer.schedule(task, new Date(), 60000);
136                 } else {
137                     logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
138                 }
139             }
140         }
141     }
142
143     /**
144      * Shut down the process.
145      */
146     private void shutdown() {
147         preShutdownOperations();
148
149         // TODO: Find a better way to shut down the model loader.
150         try {
151             // Give logs time to write to file
152             Thread.sleep(2000);
153         } catch (InterruptedException e) { // NOSONAR
154             // Nothing we can do at this point
155             logger.debug(e.getMessage());
156         }
157
158         Runtime.getRuntime().halt(1);
159     }
160
161     /**
162      * (non-Javadoc)
163      *
164      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
165      */
166     @Override
167     public Response loadModel(String modelid) {
168         return Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
169     }
170
171     /**
172      * (non-Javadoc)
173      *
174      * @see org.onap.aai.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
175      */
176     @Override
177     public Response saveModel(String modelid, String modelname) {
178         return Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}").build();
179     }
180
181     @Override
182     public Response ingestModel(String modelName, String modelVersion, String payload) throws IOException {
183         boolean success;
184
185         if (config.getIngestSimulatorEnabled()) {
186             try {
187                 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
188
189                 List<Artifact> catalogArtifacts = new ArrayList<>();
190                 List<Artifact> modelArtifacts = new ArrayList<>();
191
192                 IArtifactInfo artifactInfo = new ArtifactInfoImpl();
193                 ((ArtifactInfoImpl) artifactInfo).setArtifactName(modelName);
194                 ((ArtifactInfoImpl) artifactInfo).setArtifactVersion(modelVersion);
195
196                 byte[] csarFile = Base64.getDecoder().decode(payload);
197
198                 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Generating xml models from test artifact");
199
200                 new ArtifactDownloadManager(client, config, new BabelServiceClientFactory()).processToscaArtifacts(
201                         modelArtifacts, catalogArtifacts, csarFile, artifactInfo, "test-transaction-id", modelVersion);
202
203                 List<IArtifactInfo> artifacts = new ArrayList<>();
204                 artifacts.add(artifactInfo);
205                 INotificationData notificationData = new NotificationDataImpl();
206                 ((NotificationDataImpl) notificationData).setDistributionID("TestDistributionID");
207
208                 logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Loading xml models from test artifact");
209
210                 success = new ArtifactDeploymentManager(client, config).deploy(notificationData, artifacts,
211                         modelArtifacts, catalogArtifacts);
212
213             } catch (Exception e) {
214                 return Response.serverError().entity(e).build();
215             }
216         } else {
217             logger.debug("Simulation interface disabled");
218             success = false;
219         }
220
221         Response response;
222         if (success) {
223             response = Response.ok().build();
224         } else {
225             response = Response.serverError().build();
226         }
227
228         return response;
229     }
230 }