Change the header to SO
[so.git] / adapters / mso-adapter-utils / src / main / java / org / openecomp / mso / cloud / CloudConfigFactory.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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
21 package org.openecomp.mso.cloud;
22
23
24 import java.io.IOException;
25 import java.io.Serializable;
26 import java.util.concurrent.TimeUnit;
27 import java.util.concurrent.locks.ReentrantReadWriteLock;
28
29 import javax.ejb.ConcurrencyManagement;
30 import javax.ejb.ConcurrencyManagementType;
31 import javax.ejb.LocalBean;
32 import javax.ejb.Schedule;
33 import javax.ejb.Singleton;
34 import javax.ws.rs.GET;
35 import javax.ws.rs.Path;
36 import javax.ws.rs.PathParam;
37 import javax.ws.rs.Produces;
38 import javax.ws.rs.core.Response;
39
40 import org.codehaus.jackson.JsonParseException;
41 import org.codehaus.jackson.map.JsonMappingException;
42
43 import org.openecomp.mso.logger.MsoLogger;
44 import org.openecomp.mso.openstack.exceptions.MsoCloudIdentityNotFound;
45 import org.openecomp.mso.openstack.utils.MsoHeatUtils;
46 import org.openecomp.mso.openstack.utils.MsoKeystoneUtils;
47 import org.openecomp.mso.openstack.utils.MsoNeutronUtils;
48 import org.openecomp.mso.properties.MsoPropertiesException;
49 import org.openecomp.mso.logger.MessageEnum;
50
51 /**
52  * This class returns a cloud Config instances
53  *
54  *
55  */
56
57 @Singleton(name = "CloudConfigFactory")
58 @ConcurrencyManagement(ConcurrencyManagementType.BEAN)
59 @LocalBean
60 @Path("/cloud")
61 public class CloudConfigFactory implements Serializable {
62
63     private static final long serialVersionUID = 2956662716453261085L;
64
65     private static CloudConfig cloudConfigCache = new CloudConfig ();
66
67     protected static String prefixMsoPropertiesPath = System.getProperty ("mso.config.path");
68
69     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
70
71     private static int refreshTimer;
72
73     private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock ();
74
75     static {
76         if (prefixMsoPropertiesPath == null) {
77             prefixMsoPropertiesPath = "";
78         }
79     }
80
81     public void initializeCloudConfig (String filePath, int refreshTimer) throws MsoCloudIdentityNotFound {
82
83         rwl.writeLock ().lock ();
84         try {
85             cloudConfigCache.loadCloudConfig (prefixMsoPropertiesPath + filePath, refreshTimer);
86             LOGGER.info (MessageEnum.RA_CONFIG_LOAD, prefixMsoPropertiesPath + filePath, "", "");
87         } catch (JsonParseException e) {
88             LOGGER.error (MessageEnum.RA_CONFIG_EXC, "Error parsing cloud config file " + filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonParseException", e);
89         } catch (JsonMappingException e) {
90             LOGGER.error (MessageEnum.RA_CONFIG_EXC, "Error parsing cloud config file " + filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonMappingException", e);
91         } catch (IOException e) {
92             LOGGER.error (MessageEnum.RA_CONFIG_NOT_FOUND, filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - config not found", e);
93         } finally {
94             rwl.writeLock ().unlock ();
95         }
96     }
97
98     public void changeMsoPropertiesFilePath (String newMsoPropPath) {
99         rwl.writeLock ().lock ();
100         try {
101             CloudConfigFactory.cloudConfigCache.configFilePath = prefixMsoPropertiesPath + newMsoPropPath;
102         } finally {
103             rwl.writeLock ().unlock ();
104         }
105     }
106
107     public CloudConfigFactory () {
108     }
109
110     public CloudConfig getCloudConfig () {
111         rwl.readLock ().lock ();
112         try {
113             if (cloudConfigCache.isValidCloudConfig()) {
114                 return cloudConfigCache.clone ();
115             } else {
116                 return new CloudConfig();
117             }
118         } finally {
119             rwl.readLock ().unlock ();
120         }
121     }
122
123     /**
124      * This method is not intended to be called, it's used to refresh the config
125      * automatically
126      *
127      * @return true if Properties have been reloaded, false otherwise
128      */
129     @Schedule(minute = "*/1", hour = "*", persistent = false)
130     public void reloadCloudConfig () {
131
132         try {
133             if (!rwl.writeLock ().tryLock () && !rwl.writeLock ().tryLock (30L, TimeUnit.SECONDS)) {
134                 LOGGER.debug ("Busy write lock on mso cloud config factory, skipping the reloading");
135                 return;
136             }
137         } catch (InterruptedException e1) {
138             LOGGER.debug ("Interrupted while trying to acquire write lock on cloud config factory, skipping the reloading");
139             Thread.currentThread ().interrupt ();
140             return;
141         }
142         try {
143             //LOGGER.debug ("Processing a reload of the mso properties file entries");
144             try {
145
146                 if (refreshTimer <= 1) {
147                     CloudConfig oldCloudConfig = null;
148                     if (cloudConfigCache.isValidCloudConfig()) {
149                         oldCloudConfig = cloudConfigCache.clone();
150                     }
151                     cloudConfigCache.reloadPropertiesFile ();
152                     refreshTimer = cloudConfigCache.refreshTimerInMinutes;
153                     if (!cloudConfigCache.equals(oldCloudConfig)) {
154                         LOGGER.info (MessageEnum.RA_CONFIG_LOAD, prefixMsoPropertiesPath + cloudConfigCache.configFilePath, "", "");
155                     }
156
157                 } else {
158                     --refreshTimer;
159                 }
160
161             } catch (JsonParseException e) {
162                 LOGGER.error (MessageEnum.RA_CONFIG_EXC,
163                               "Error parsing cloud config file " + cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonParseException",
164                               e);
165             } catch (JsonMappingException e) {
166                 LOGGER.error (MessageEnum.RA_CONFIG_EXC,
167                               "Error parsing cloud config file " + cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonMappingException",
168                               e);
169             } catch (IOException e) {
170                 LOGGER.error (MessageEnum.RA_CONFIG_NOT_FOUND, cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - config not found", e);
171             }
172         } catch (Exception e) {
173             LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Global issue while reloading", "", "", MsoLogger.ErrorCode.DataError, "Exception - Global issue while reloading\"", e);
174         } finally {
175             rwl.writeLock ().unlock ();
176         }
177     }
178
179     @GET
180     @Path("/showConfig")
181     @Produces("text/plain")
182     public Response showCloudConfig () {
183         CloudConfig cloudConfig = this.getCloudConfig ();
184         if (cloudConfig != null) {
185             StringBuffer response = new StringBuffer ();
186             response.append ("Cloud Sites:\n");
187             for (CloudSite site : cloudConfig.getCloudSites ().values ()) {
188                 response.append (site.toString () + "\n");
189             }
190     
191             response.append ("\n\nCloud Identity Services:\n");
192             for (CloudIdentity identity : cloudConfig.getIdentityServices ().values ()) {
193                 response.append (identity.toString () + "\n");
194             }
195     
196             return Response.status (200).entity (response).build ();
197         } else {
198             return Response.status (500).entity ("Cloud Config has not been loaded properly, this could be due to a bad JSON structure (Check the logs for additional details)").build ();
199         }
200     }
201
202     @GET
203     @Path("/resetClientCaches")
204     @Produces("text/plain")
205     public Response resetClientCaches () {
206         // Reset all cached clients/credentials
207         MsoKeystoneUtils.adminCacheReset ();
208         MsoHeatUtils.heatCacheReset ();
209         MsoNeutronUtils.neutronCacheReset ();
210
211         String response = "Client caches reset.  All entries removed.";
212         return Response.status (200).entity (response).build ();
213     }
214
215     @GET
216     @Path("/cleanupClientCaches")
217     @Produces("text/plain")
218     public Response cleanupClientCaches () {
219         // Reset all cached clients/credentials
220         MsoKeystoneUtils.adminCacheCleanup ();
221         MsoHeatUtils.heatCacheCleanup ();
222         MsoNeutronUtils.neutronCacheCleanup ();
223
224         String response = "Client caches cleaned up.  All expired entries removed";
225         return Response.status (200).entity (response).build ();
226     }
227
228     @GET
229     @Path("/encryptPassword/{pwd}")
230     @Produces("text/plain")
231     public Response encryptPassword (@PathParam("pwd") String pwd) {
232         String encryptedPassword = CloudIdentity.encryptPassword (pwd);
233
234         String response = "Encrypted Password = " + encryptedPassword;
235         return Response.status (200).entity (response).build ();
236     }
237 }