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