Ensure shutdown hook is called on docker stop
[aai/model-loader.git] / src / main / java / org / openecomp / modelloader / service / ModelLoaderService.java
1 /**
2  * ============LICENSE_START=======================================================
3  * Model Loader
4  * ================================================================================
5  * Copyright © 2017 AT&T Intellectual Property.
6  * Copyright © 2017 Amdocs
7  * All rights reserved.
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * http://www.apache.org/licenses/LICENSE-2.0
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  *
20  * ECOMP and OpenECOMP are trademarks
21  * and service marks of AT&T Intellectual Property.
22  */
23 package org.openecomp.modelloader.service;
24
25 import org.openecomp.sdc.api.IDistributionClient;
26 import org.openecomp.sdc.api.results.IDistributionClientResult;
27 import org.openecomp.sdc.impl.DistributionClientFactory;
28 import org.openecomp.sdc.utils.DistributionActionResultEnum;
29
30 import org.openecomp.cl.api.Logger;
31 import org.openecomp.cl.eelf.LoggerFactory;
32 import org.openecomp.modelloader.config.ModelLoaderConfig;
33 import org.openecomp.modelloader.entity.model.ModelArtifactHandler;
34 import org.openecomp.modelloader.notification.EventCallback;
35
36 import java.io.FileInputStream;
37 import java.io.IOException;
38 import java.util.Date;
39 import java.util.Properties;
40 import java.util.Timer;
41 import java.util.TimerTask;
42
43 import javax.servlet.http.HttpServletRequest;
44 import javax.ws.rs.core.Response;
45
46 /**
47  * Service class in charge of managing the negotiating model loading
48  * capabilities between AAI and an ASDC.
49  */
50 public class ModelLoaderService implements ModelLoaderInterface {
51         
52         protected static final String FILESEP = (System.getProperty("file.separator") == null) ? "/"
53             : System.getProperty("file.separator");
54
55         protected static final String CONFIG_DIR = System.getProperty("CONFIG_HOME") + FILESEP;
56         protected static final String CONFIG_AUTH_LOCATION = CONFIG_DIR + "auth" + FILESEP;
57         protected static final String CONFIG_FILE = CONFIG_DIR + "model-loader.properties";
58
59         private IDistributionClient client;
60         private ModelLoaderConfig config;
61         private Timer timer = null;
62
63         static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
64
65         /**
66          * Responsible for loading configuration files and calling initialization.
67          */
68         public ModelLoaderService() {
69                 start();
70         }
71
72         protected void start() {
73                 // Load model loader system configuration
74                 logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
75                 Properties configProperties = new Properties();
76                 try {
77                         configProperties.load(new FileInputStream(CONFIG_FILE));
78                 } catch (IOException e) {
79                         String errorMsg = "Failed to load configuration: " + e.getMessage();
80                         logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
81                         shutdown();
82                 }
83
84                 config = new ModelLoaderConfig(configProperties, CONFIG_AUTH_LOCATION);
85                 init();
86                 
87                 Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
88                         public void run() {
89                                 preShutdownOperations();
90                         }
91                 }));
92         }
93         
94         /**
95          * Responsible for stopping the connection to the distribution client before
96          * the resource is destroyed.
97          */
98         protected void preShutdownOperations() {
99                 logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
100                 if (client != null) {
101                         client.stop();
102                 }
103         }
104
105         /**
106          * Responsible for loading configuration files, initializing model
107          * distribution clients, and starting them.
108          */
109         protected void init() {
110                 // Initialize distribution client
111                 logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
112                 client = DistributionClientFactory.createDistributionClient();
113                 EventCallback callback = new EventCallback(client, config);
114                 
115                 IDistributionClientResult initResult = client.init(config, callback);
116
117                 if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
118                         String errorMsg = "Failed to initialize distribution client: "
119                                         + initResult.getDistributionMessageResult();
120                         logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
121                         
122                         // Kick off a timer to retry the SDC connection
123                         timer = new Timer();
124                         TimerTask task = new SdcConnectionJob(client, config, callback, timer);
125                         timer.schedule(task, new Date(), 60000);
126                 }
127                 else {
128                         // Start distribution client
129                         logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
130                         IDistributionClientResult startResult = client.start();
131                         if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
132                                 String errorMsg = "Failed to start distribution client: "
133                                                 + startResult.getDistributionMessageResult();
134                                 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
135
136                                 // Kick off a timer to retry the SDC connection
137                                 timer = new Timer();
138                                 TimerTask task = new SdcConnectionJob(client, config, callback, timer);
139                                 timer.schedule(task, new Date(), 60000);
140                         }
141                         else {
142                                 logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
143                         }
144                 }
145         }
146
147         /**
148          * Shut down the process.
149          */
150         private void shutdown() {
151                 preShutdownOperations();
152
153                 // TODO: Find a better way to shut down the model loader.
154                 try {
155                         // Give logs time to write to file
156                         Thread.sleep(2000);
157                 } catch (InterruptedException e) {
158                         // Nothing we can do at this point
159                 }
160
161                 Runtime.getRuntime().halt(1);
162         }
163
164         /** (non-Javadoc)
165          * @see org.openecomp.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
166          */
167         @Override
168         public Response loadModel(String modelid) {
169                 Response response = Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
170
171                 return response;
172         }
173
174         /** (non-Javadoc)
175          * @see org.openecomp.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
176          */
177         @Override
178         public Response saveModel(String modelid, String modelname) {
179                 Response response = Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}")
180                                 .build();
181
182                 return response;
183         }
184
185         @Override
186         public Response ingestModel(String modelid, HttpServletRequest req, String payload)
187                         throws IOException {
188                 Response response;
189
190                 if (config.getIngestSimulatorEnabled()) {
191                         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
192
193                         ModelArtifactHandler handler = new ModelArtifactHandler(config);
194                         handler.loadModelTest(payload.getBytes());
195
196                         response = Response.ok().build();
197                 } else {
198                         logger.debug("Simulation interface disabled");
199                         response = Response.serverError().build();
200                 }
201
202                 return response;
203         }
204 }