AT&T 1712 and 1802 release code
[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 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 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                 return cloudConfigCache.clone ();
97             } else {
98                 return new CloudConfig();
99             }
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      * @return true if Properties have been reloaded, false otherwise
110      */
111     @Schedule(minute = "*/1", hour = "*", persistent = false)
112     public void reloadCloudConfig () {
113
114         try {
115             if (!rwl.writeLock ().tryLock () && !rwl.writeLock ().tryLock (30L, TimeUnit.SECONDS)) {
116                 LOGGER.debug ("Busy write lock on mso cloud config factory, skipping the reloading");
117                 return;
118             }
119         } catch (InterruptedException e1) {
120             LOGGER.debug ("Interrupted while trying to acquire write lock on cloud config factory, skipping the reloading");
121             Thread.currentThread ().interrupt ();
122             return;
123         }
124         try {
125             //LOGGER.debug ("Processing a reload of the mso properties file entries");
126             try {
127
128                 if (refreshTimer <= 1) {
129                     CloudConfig oldCloudConfig = null;
130                     if (cloudConfigCache.isValidCloudConfig()) {
131                         oldCloudConfig = cloudConfigCache.clone();
132                     }
133                     cloudConfigCache.reloadPropertiesFile ();
134                     refreshTimer = cloudConfigCache.refreshTimerInMinutes;
135                     if (!cloudConfigCache.equals(oldCloudConfig)) {
136                         LOGGER.info (MessageEnum.RA_CONFIG_LOAD, prefixMsoPropertiesPath + cloudConfigCache.configFilePath, "", "");
137                     }
138
139                 } else {
140                     --refreshTimer;
141                 }
142
143             } catch (JsonParseException e) {
144                 LOGGER.error (MessageEnum.RA_CONFIG_EXC,
145                               "Error parsing cloud config file " + cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonParseException",
146                               e);
147             } catch (JsonMappingException e) {
148                 LOGGER.error (MessageEnum.RA_CONFIG_EXC,
149                               "Error parsing cloud config file " + cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - JsonMappingException",
150                               e);
151             } catch (IOException e) {
152                 LOGGER.error (MessageEnum.RA_CONFIG_NOT_FOUND, cloudConfigCache.configFilePath, "", "", MsoLogger.ErrorCode.DataError, "Exception - config not found", e);
153             }
154         } catch (Exception e) {
155             LOGGER.error (MessageEnum.LOAD_PROPERTIES_FAIL, "Unknown. Global issue while reloading", "", "", MsoLogger.ErrorCode.DataError, "Exception - Global issue while reloading\"", e);
156         } finally {
157             rwl.writeLock ().unlock ();
158         }
159     }
160
161     @GET
162     @Path("/showConfig")
163     @Produces("text/plain")
164     public Response showCloudConfig () {
165         CloudConfig cloudConfig = this.getCloudConfig();
166         StringBuffer response = new StringBuffer();
167         response.append("Cloud Sites:\n");
168         for (CloudSite site : cloudConfig.getCloudSites().values()) {
169             response.append(site.toString()).append("\n");
170         }
171         response.append("\n\nCloud Identity Services:\n");
172         for (CloudIdentity identity : cloudConfig.getIdentityServices().values()) {
173             response.append(identity.toString()).append("\n");
174         }
175         return Response.status(200).entity(response).build();
176     }
177
178     @GET
179     @Path("/resetClientCaches")
180     @Produces("text/plain")
181     public Response resetClientCaches () {
182         // Reset all cached clients/credentials
183         MsoKeystoneUtils.adminCacheReset ();
184         MsoHeatUtils.heatCacheReset ();
185         MsoNeutronUtils.neutronCacheReset ();
186         String response = "Client caches reset. All entries removed.";
187         return Response.status (200).entity (response).build ();
188     }
189
190     @GET
191     @Path("/cleanupClientCaches")
192     @Produces("text/plain")
193     public Response cleanupClientCaches () {
194         // Reset all cached clients/credentials
195         MsoKeystoneUtils.adminCacheCleanup ();
196         MsoHeatUtils.heatCacheCleanup ();
197         MsoNeutronUtils.neutronCacheCleanup ();
198         String response = "Client caches cleaned up. All expired entries removed.";
199         return Response.status (200).entity (response).build ();
200     }
201
202     @GET
203     @Path("/encryptPassword/{pwd}")
204     @Produces("text/plain")
205     public Response encryptPassword (@PathParam("pwd") String pwd) {
206         String encryptedPassword = CloudIdentity.encryptPassword (pwd);
207
208         String response = "Encrypted Password = " + encryptedPassword;
209         return Response.status (200).entity (response).build ();
210     }
211 }