Merge "Reorder modifiers"
[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 import java.io.IOException;
24 import java.io.Serializable;
25 import java.util.concurrent.TimeUnit;
26 import java.util.concurrent.locks.ReentrantReadWriteLock;
27 import javax.ejb.ConcurrencyManagement;
28 import javax.ejb.ConcurrencyManagementType;
29 import javax.ejb.LocalBean;
30 import javax.ejb.Schedule;
31 import javax.ejb.Singleton;
32 import javax.ws.rs.GET;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.PathParam;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.core.Response;
37
38 import org.openecomp.mso.logger.MessageEnum;
39 import org.openecomp.mso.logger.MsoLogger;
40 import org.openecomp.mso.openstack.exceptions.MsoCloudIdentityNotFound;
41 import org.openecomp.mso.openstack.utils.MsoHeatUtils;
42 import org.openecomp.mso.openstack.utils.MsoKeystoneUtils;
43 import org.openecomp.mso.openstack.utils.MsoNeutronUtils;
44
45 import com.fasterxml.jackson.core.JsonParseException;
46 import com.fasterxml.jackson.databind.JsonMappingException;
47
48 /**
49  * This class returns a cloud Config instances
50  */
51
52 @Singleton(name = "CloudConfigFactory")
53 @ConcurrencyManagement(ConcurrencyManagementType.BEAN)
54 @LocalBean
55 @Path("/cloud")
56 public class CloudConfigFactory implements Serializable {
57
58     private static final long serialVersionUID = 2956662716453261085L;
59
60     private static CloudConfig cloudConfigCache = new CloudConfig();
61
62     protected static String prefixMsoPropertiesPath = System.getProperty ("mso.config.path");
63
64     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger (MsoLogger.Catalog.RA);
65
66     private static int refreshTimer;
67
68     private static final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock ();
69
70     static {
71         if (prefixMsoPropertiesPath == null) {
72             prefixMsoPropertiesPath = "";
73         }
74     }
75     
76     public void initializeCloudConfig (String filePath, int refreshTimer) throws MsoCloudIdentityNotFound {
77         rwl.writeLock ().lock ();
78         try {
79             cloudConfigCache.loadCloudConfig (prefixMsoPropertiesPath + filePath, refreshTimer);
80             LOGGER.info (MessageEnum.RA_CONFIG_LOAD, prefixMsoPropertiesPath + filePath, "", "");
81         } catch (JsonParseException e) {
82             LOGGER.error (MessageEnum.RA_CONFIG_EXC, "Error parsing cloud config file " + filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonParseException", e);
83         } catch (JsonMappingException e) {
84             LOGGER.error (MessageEnum.RA_CONFIG_EXC, "Error parsing cloud config file " + filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonMappingException", e);
85         } catch (IOException e) {
86             LOGGER.error (MessageEnum.RA_CONFIG_NOT_FOUND, filePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - config not found", e);
87         } finally {
88             rwl.writeLock ().unlock ();
89         }
90     }
91
92     public CloudConfig getCloudConfig () {
93         rwl.readLock ().lock ();
94         try {
95             if (!cloudConfigCache.isValidCloudConfig()) {
96                 // Not ideal, but better than returning an invalid object
97                 throw new IllegalStateException("No valid CloudConfig is loaded");
98             }
99             return cloudConfigCache.clone ();
100         } finally {
101             rwl.readLock ().unlock ();
102         }
103     }
104
105     /**
106      * This method is not intended to be called, it's used to refresh the config
107      * automatically
108      */
109     @Schedule(minute = "*/1", hour = "*", persistent = false)
110     public void reloadCloudConfig () {
111
112         try {
113             if (!rwl.writeLock ().tryLock () && !rwl.writeLock ().tryLock (30L, TimeUnit.SECONDS)) {
114                 LOGGER.debug ("Busy write lock on mso cloud config factory, skipping the reloading");
115                 return;
116             }
117         } catch (InterruptedException e1) {
118             LOGGER.debug ("Interrupted while trying to acquire write lock on cloud config factory, skipping the reloading");
119             Thread.currentThread ().interrupt ();
120             return;
121         }
122         try {
123             //LOGGER.debug ("Processing a reload of the mso properties file entries");
124             try {
125
126                 if (refreshTimer <= 1) {
127                     CloudConfig oldCloudConfig = null;
128                     if (cloudConfigCache.isValidCloudConfig()) {
129                         oldCloudConfig = cloudConfigCache.clone();
130                     }
131                     cloudConfigCache.reloadPropertiesFile ();
132                     refreshTimer = cloudConfigCache.refreshTimerInMinutes;
133                     if (!cloudConfigCache.equals(oldCloudConfig)) {
134                         LOGGER.info (MessageEnum.RA_CONFIG_LOAD, prefixMsoPropertiesPath + cloudConfigCache.configFilePath, "", "");
135                     }
136
137                 } else {
138                     --refreshTimer;
139                 }
140
141             } catch (JsonParseException e) {
142                 LOGGER.error (MessageEnum.RA_CONFIG_EXC,
143                               "Error parsing cloud config file " + cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonParseException",
144                               e);
145             } catch (JsonMappingException e) {
146                 LOGGER.error (MessageEnum.RA_CONFIG_EXC,
147                               "Error parsing cloud config file " + cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonMappingException",
148                               e);
149             } catch (IOException e) {
150                 LOGGER.error (MessageEnum.RA_CONFIG_NOT_FOUND, cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - config not found", e);
151             }
152         } catch (Exception e) {
153             LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Global issue while reloading", "", "", MsoLogger.ErrorCode.DataError, "Exception - Global issue while reloading\"", e);
154         } finally {
155             rwl.writeLock ().unlock ();
156         }
157     }
158
159     @GET
160     @Path("/showConfig")
161     @Produces("text/plain")
162     public Response showCloudConfig () {
163         CloudConfig cloudConfig = this.getCloudConfig();
164         StringBuffer response = new StringBuffer();
165         response.append("Cloud Sites:\n");
166         for (CloudSite site : cloudConfig.getCloudSites().values()) {
167             response.append(site.toString()).append("\n");
168         }
169         response.append("\n\nCloud Identity Services:\n");
170         for (CloudIdentity identity : cloudConfig.getIdentityServices().values()) {
171             response.append(identity.toString()).append("\n");
172         }
173         return Response.status(200).entity(response).build();
174     }
175
176     @GET
177     @Path("/resetClientCaches")
178     @Produces("text/plain")
179     public Response resetClientCaches () {
180         // Reset all cached clients/credentials
181         MsoKeystoneUtils.adminCacheReset ();
182         MsoHeatUtils.heatCacheReset ();
183         MsoNeutronUtils.neutronCacheReset ();
184         String response = "Client caches reset. All entries removed.";
185         return Response.status (200).entity (response).build ();
186     }
187
188     @GET
189     @Path("/cleanupClientCaches")
190     @Produces("text/plain")
191     public Response cleanupClientCaches () {
192         // Reset all cached clients/credentials
193         MsoKeystoneUtils.adminCacheCleanup ();
194         MsoHeatUtils.heatCacheCleanup ();
195         MsoNeutronUtils.neutronCacheCleanup ();
196         String response = "Client caches cleaned up. All expired entries removed.";
197         return Response.status (200).entity (response).build ();
198     }
199
200     @GET
201     @Path("/encryptPassword/{pwd}")
202     @Produces("text/plain")
203     public Response encryptPassword (@PathParam("pwd") String pwd) {
204         String encryptedPassword = CloudIdentity.encryptPassword (pwd);
205
206         String response = "Encrypted Password = " + encryptedPassword;
207         return Response.status (200).entity (response).build ();
208     }
209 }