Update license date and text
[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 org.openecomp.sdc.api.IDistributionClient;
24 import org.openecomp.sdc.api.results.IDistributionClientResult;
25 import org.openecomp.sdc.impl.DistributionClientFactory;
26 import org.openecomp.sdc.utils.DistributionActionResultEnum;
27 import org.onap.aai.modelloader.config.ModelLoaderConfig;
28 import org.onap.aai.modelloader.entity.model.ModelArtifactHandler;
29 import org.onap.aai.modelloader.notification.EventCallback;
30 import org.onap.aai.cl.api.Logger;
31 import org.onap.aai.cl.eelf.LoggerFactory;
32
33 import java.io.FileInputStream;
34 import java.io.IOException;
35 import java.util.Date;
36 import java.util.Properties;
37 import java.util.Timer;
38 import java.util.TimerTask;
39
40 import javax.servlet.http.HttpServletRequest;
41 import javax.ws.rs.core.Response;
42
43 /**
44  * Service class in charge of managing the negotiating model loading
45  * capabilities between AAI and an ASDC.
46  */
47 public class ModelLoaderService implements ModelLoaderInterface {
48         
49         protected static final String FILESEP = (System.getProperty("file.separator") == null) ? "/"
50             : System.getProperty("file.separator");
51
52         protected static final String CONFIG_DIR = System.getProperty("CONFIG_HOME") + FILESEP;
53         protected static final String CONFIG_AUTH_LOCATION = CONFIG_DIR + "auth" + FILESEP;
54         protected static final String CONFIG_FILE = CONFIG_DIR + "model-loader.properties";
55
56         private IDistributionClient client;
57         private ModelLoaderConfig config;
58         private Timer timer = null;
59
60         static Logger logger = LoggerFactory.getInstance().getLogger(ModelLoaderService.class.getName());
61
62         /**
63          * Responsible for loading configuration files and calling initialization.
64          */
65         public ModelLoaderService() {
66                 start();
67         }
68
69         protected void start() {
70                 // Load model loader system configuration
71                 logger.info(ModelLoaderMsgs.LOADING_CONFIGURATION);
72                 Properties configProperties = new Properties();
73                 try {
74                         configProperties.load(new FileInputStream(CONFIG_FILE));
75                 } catch (IOException e) {
76                         String errorMsg = "Failed to load configuration: " + e.getMessage();
77                         logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
78                         shutdown();
79                 }
80
81                 config = new ModelLoaderConfig(configProperties, CONFIG_AUTH_LOCATION);
82                 init();
83                 
84                 Runtime.getRuntime().addShutdownHook(new Thread(new Runnable(){
85                         public void run() {
86                                 preShutdownOperations();
87                         }
88                 }));
89         }
90         
91         /**
92          * Responsible for stopping the connection to the distribution client before
93          * 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
104          * distribution clients, and starting them.
105          */
106         protected void init() {
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 = "Failed to initialize distribution client: "
116                                         + initResult.getDistributionMessageResult();
117                         logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
118                         
119                         // Kick off a timer to retry the SDC connection
120                         timer = new Timer();
121                         TimerTask task = new SdcConnectionJob(client, config, callback, timer);
122                         timer.schedule(task, new Date(), 60000);
123                 }
124                 else {
125                         // Start distribution client
126                         logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
127                         IDistributionClientResult startResult = client.start();
128                         if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
129                                 String errorMsg = "Failed to start distribution client: "
130                                                 + startResult.getDistributionMessageResult();
131                                 logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
132
133                                 // Kick off a timer to retry the SDC connection
134                                 timer = new Timer();
135                                 TimerTask task = new SdcConnectionJob(client, config, callback, timer);
136                                 timer.schedule(task, new Date(), 60000);
137                         }
138                         else {
139                                 logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
140                         }
141                 }
142         }
143
144         /**
145          * Shut down the process.
146          */
147         private void shutdown() {
148                 preShutdownOperations();
149
150                 // TODO: Find a better way to shut down the model loader.
151                 try {
152                         // Give logs time to write to file
153                         Thread.sleep(2000);
154                 } catch (InterruptedException e) {
155                         // Nothing we can do at this point
156                 }
157
158                 Runtime.getRuntime().halt(1);
159         }
160
161         /** (non-Javadoc)
162          * @see org.onap.aai.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
163          */
164         @Override
165         public Response loadModel(String modelid) {
166                 Response response = Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
167
168                 return response;
169         }
170
171         /** (non-Javadoc)
172          * @see org.onap.aai.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
173          */
174         @Override
175         public Response saveModel(String modelid, String modelname) {
176                 Response response = Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}")
177                                 .build();
178
179                 return response;
180         }
181
182         @Override
183         public Response ingestModel(String modelid, HttpServletRequest req, String payload)
184                         throws IOException {
185                 Response response;
186
187                 if (config.getIngestSimulatorEnabled()) {
188                         logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
189
190                         ModelArtifactHandler handler = new ModelArtifactHandler(config);
191                         handler.loadModelTest(payload.getBytes());
192
193                         response = Response.ok().build();
194                 } else {
195                         logger.debug("Simulation interface disabled");
196                         response = Response.serverError().build();
197                 }
198
199                 return response;
200         }
201 }