aeaa6f42f3e8a4c690155309473d6098808c6097
[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
88   @Override
89   public void finalize() {
90     preShutdownOperations();
91   }
92
93   /**
94    * Responsible for stopping the connection to the distribution client before
95    * the resource is destroyed.
96    */
97   protected void preShutdownOperations() {
98     logger.info(ModelLoaderMsgs.STOPPING_CLIENT);
99     if (client != null) {
100       client.stop();
101     }
102   }
103
104   /**
105    * Responsible for loading configuration files, initializing model
106    * distribution clients, and starting them.
107    */
108   protected void init() {
109     // Initialize distribution client
110     logger.debug(ModelLoaderMsgs.INITIALIZING, "Initializing distribution client...");
111     client = DistributionClientFactory.createDistributionClient();
112     EventCallback callback = new EventCallback(client, config);
113
114     IDistributionClientResult initResult = client.init(config, callback);
115
116     if (initResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
117       String errorMsg = "Failed to initialize distribution client: "
118           + initResult.getDistributionMessageResult();
119       logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
120
121       // Kick off a timer to retry the SDC connection
122       timer = new Timer();
123       TimerTask task = new SdcConnectionJob(client, config, callback, timer);
124       timer.schedule(task, new Date(), 60000);
125     }
126     else {
127       // Start distribution client
128       logger.debug(ModelLoaderMsgs.INITIALIZING, "Starting distribution client...");
129       IDistributionClientResult startResult = client.start();
130       if (startResult.getDistributionActionResult() != DistributionActionResultEnum.SUCCESS) {
131         String errorMsg = "Failed to start distribution client: "
132             + startResult.getDistributionMessageResult();
133         logger.error(ModelLoaderMsgs.ASDC_CONNECTION_ERROR, errorMsg);
134
135         // Kick off a timer to retry the SDC connection
136         timer = new Timer();
137         TimerTask task = new SdcConnectionJob(client, config, callback, timer);
138         timer.schedule(task, new Date(), 60000);
139       }
140       else {
141         logger.info(ModelLoaderMsgs.INITIALIZING, "Connection to SDC established");
142       }
143     }
144   }
145
146   /**
147    * Shut down the process.
148    */
149   private void shutdown() {
150     preShutdownOperations();
151
152     // TODO: Find a better way to shut down the model loader.
153     try {
154       // Give logs time to write to file
155       Thread.sleep(2000);
156     } catch (InterruptedException e) {
157       // Nothing we can do at this point
158     }
159
160     Runtime.getRuntime().halt(1);
161   }
162
163   /** (non-Javadoc)
164    * @see org.openecomp.modelloader.service.ModelLoaderInterface#loadModel(java.lang.String)
165    */
166   @Override
167   public Response loadModel(String modelid) {
168     Response response = Response.ok("{\"model_loaded\":\"" + modelid + "\"}").build();
169
170     return response;
171   }
172
173   /** (non-Javadoc)
174    * @see org.openecomp.modelloader.service.ModelLoaderInterface#saveModel(java.lang.String, java.lang.String)
175    */
176   @Override
177   public Response saveModel(String modelid, String modelname) {
178     Response response = Response.ok("{\"model_saved\":\"" + modelid + "-" + modelname + "\"}")
179         .build();
180
181     return response;
182   }
183
184   @Override
185   public Response ingestModel(String modelid, HttpServletRequest req, String payload)
186       throws IOException {
187     Response response;
188
189     if (config.getIngestSimulatorEnabled()) {
190       logger.info(ModelLoaderMsgs.DISTRIBUTION_EVENT, "Received test artifact");
191
192       ModelArtifactHandler handler = new ModelArtifactHandler(config);
193       handler.loadModelTest(payload.getBytes());
194
195       response = Response.ok().build();
196     } else {
197       logger.debug("Simulation interface disabled");
198       response = Response.serverError().build();
199     }
200
201     return response;
202   }
203 }