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