Merge "Reorder modifiers"
[so.git] / adapters / mso-adapter-utils / src / main / java / org / openecomp / mso / cloud / CloudConfig.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.FileReader;
24 import java.io.IOException;
25 import java.util.Collections;
26 import java.util.HashMap;
27 import java.util.Map;
28 import java.util.Map.Entry;
29 import java.util.Optional;
30
31 import org.openecomp.mso.logger.MsoLogger;
32 import org.openecomp.mso.openstack.exceptions.MsoCloudIdentityNotFound;
33
34 import com.fasterxml.jackson.annotation.JsonProperty;
35 import com.fasterxml.jackson.annotation.JsonRootName;
36 import com.fasterxml.jackson.core.JsonParseException;
37 import com.fasterxml.jackson.databind.DeserializationFeature;
38 import com.fasterxml.jackson.databind.JsonMappingException;
39 import com.fasterxml.jackson.databind.ObjectMapper;
40
41 /**
42  * JavaBean JSON class for a CloudConfig. This bean maps a JSON-format cloud
43  * configuration file to Java. The CloudConfig contains information about
44  * Openstack cloud configurations. It includes: 
45  * - CloudIdentity objects,representing DCP nodes (Openstack Identity Service) 
46  * - CloudSite objects, representing LCP nodes (Openstack Compute & other services)
47  *
48  * Note that this is only used to access Cloud Configurations loaded from a JSON
49  * config file, so there are no explicit property setters.
50  *
51  * This class also contains methods to query cloud sites and/or identity
52  * services by ID.
53  *
54  */
55
56 @JsonRootName("cloud_config")
57 public class CloudConfig {
58
59     private static final String CLOUD_SITE_VERSION = "2.5";
60     private static final String DEFAULT_CLOUD_SITE_ID = "default";
61     private boolean validCloudConfig = false;
62     private static ObjectMapper mapper = new ObjectMapper();
63     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA);
64     protected String configFilePath;
65     protected int refreshTimerInMinutes;
66     @JsonProperty("identity_services")
67     private Map<String, CloudIdentity> identityServices = new HashMap<>();
68     @JsonProperty("cloud_sites")
69     private Map <String, CloudSite> cloudSites = new HashMap <String, CloudSite> ();
70     @JsonProperty("cloudify_managers")
71     private Map <String, CloudifyManager> cloudifyManagers = new HashMap <String, CloudifyManager> ();
72
73     public CloudConfig() {
74         mapper.enable(DeserializationFeature.UNWRAP_ROOT_VALUE);
75         mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
76     }
77
78     /**
79      * Get a map of all identity services that have been loaded.
80      */
81     public synchronized Map<String, CloudIdentity> getIdentityServices() {
82         return identityServices;
83     }
84
85     /**
86      * Get a map of all cloud sites that have been loaded.
87      */
88     public Map<String, CloudSite> getCloudSites() {
89         return Collections.unmodifiableMap(cloudSites);
90     }
91
92         /**
93          * Get a Map of all CloudifyManagers that have been loaded.
94          * @return the Map
95          */
96     public synchronized Map <String, CloudifyManager> getCloudifyManagers () {
97         return cloudifyManagers;
98     }
99
100     /**
101      * Get a specific CloudSites, based on an ID. The ID is first checked
102      * against the regions, and if no match is found there, then against
103      * individual entries to try and find one with a CLLI that matches the ID
104      * and an AIC version of 2.5.
105      *
106      * @param id the ID to match
107      * @return an Optional of CloudSite object.
108      */
109     public synchronized Optional<CloudSite> getCloudSite(String id) {
110         if (id == null) {
111             return Optional.empty();
112         }
113         if (cloudSites.containsKey(id)) {
114             return Optional.ofNullable(cloudSites.get(id));
115         }
116         return null;
117     }
118
119      private CloudSite getCloudSiteWithClli(String clli) {
120         Optional <CloudSite> cloudSiteOptional = cloudSites.values().stream().filter(cs ->
121                 cs.getClli() != null && clli.equals(cs.getClli()) && (CLOUD_SITE_VERSION.equals(cs.getAic_version())))
122                 .findAny();
123         return cloudSiteOptional.orElse(getDefaultCloudSite(clli));
124     }
125
126     private CloudSite getDefaultCloudSite(String clli) {
127         Optional<CloudSite> cloudSiteOpt = cloudSites.values().stream()
128                 .filter(cs -> cs.getId().equalsIgnoreCase(DEFAULT_CLOUD_SITE_ID)).findAny();
129         if (cloudSiteOpt.isPresent()) {
130             CloudSite defaultCloudSite = cloudSiteOpt.get();
131             defaultCloudSite.setRegionId(clli);
132             defaultCloudSite.setId(clli);
133             return defaultCloudSite;
134         } else {
135             return null;
136         }
137     }
138
139     /**
140      * Get a specific CloudIdentity, based on an ID.
141      * 
142      * @param id
143      *            the ID to match
144      * @return a CloudIdentity, or null of no match found
145      */
146     public synchronized CloudIdentity getIdentityService(String id) {
147         if (identityServices.containsKey(id)) {
148             return identityServices.get(id);
149         }
150         return null;
151     }
152
153         /**
154          * Get a specific CloudifyManager, based on an ID.
155          * @param id the ID to match
156          * @return a CloudifyManager, or null of no match found
157          */
158         public synchronized CloudifyManager getCloudifyManager (String id) {
159                 if (cloudifyManagers.containsKey (id)) {
160                         return cloudifyManagers.get (id);
161                 }
162                 return null;
163         }
164
165     protected synchronized void reloadPropertiesFile() throws IOException, MsoCloudIdentityNotFound {
166         this.loadCloudConfig(this.configFilePath, this.refreshTimerInMinutes);
167     }
168
169     protected synchronized void loadCloudConfig(String configFile, int refreshTimer)
170             throws IOException, MsoCloudIdentityNotFound {
171
172         FileReader reader = null;
173         configFilePath = configFile;
174         this.refreshTimerInMinutes = refreshTimer;
175         this.validCloudConfig=false;
176
177         try {
178             reader = new FileReader(configFile);
179             // Parse the JSON input into a CloudConfig
180
181             CloudConfig cloudConfig = mapper.readValue(reader, CloudConfig.class);
182
183             this.cloudSites = cloudConfig.cloudSites;
184             this.identityServices = cloudConfig.identityServices;
185                 this.cloudifyManagers = cloudConfig.cloudifyManagers;
186
187             // Copy Cloud Identity IDs to CloudIdentity objects
188             for (Entry<String, CloudIdentity> entry : cloudConfig.getIdentityServices().entrySet()) {
189                 entry.getValue().setId(entry.getKey());
190             }
191
192                 // Copy Cloduify IDs to CloudifyManager objects
193                 for (Entry <String, CloudifyManager> entry : cloudConfig.getCloudifyManagers ().entrySet ()) {
194                     entry.getValue ().setId (entry.getKey ());
195                 }
196
197             // Copy Cloud Site IDs to CloudSite objects, and set up internal
198             // pointers to their corresponding identity service.
199             for (Entry<String, CloudSite> entry : cloudConfig.getCloudSites().entrySet()) {
200                 CloudSite s = entry.getValue();
201                 s.setId(entry.getKey());
202                 CloudIdentity cloudIdentity = cloudConfig.getIdentityService(s.getIdentityServiceId());
203                 s.setIdentityService(cloudIdentity);
204                 if (cloudIdentity == null) {
205                     throw new MsoCloudIdentityNotFound(s.getId()+" Cloud site refers to a non-existing identity service: "+s.getIdentityServiceId());
206                 }
207                 CloudifyManager cloudifyManager = cloudConfig.getCloudifyManager(s.getCloudifyId());
208                 s.setCloudifyManager(cloudifyManager);
209             }
210             this.validCloudConfig=true;
211             
212         } finally {
213             try {
214                 if (reader != null) {
215                     reader.close();
216                 }
217             } catch (IOException e) {
218                 LOGGER.debug("Exception while closing reader for file:" + configFilePath, e);
219             }
220         }
221     }
222
223     public String getConfigFilePath() {
224         return configFilePath;
225     }
226
227     /**
228      * @return the validCouldConfig
229      */
230     public synchronized boolean isValidCloudConfig() {
231         return validCloudConfig;
232     }
233
234     @Override
235     public synchronized CloudConfig clone() {
236         CloudConfig ccCopy = new CloudConfig();
237         for (Entry<String, CloudIdentity> e : identityServices.entrySet()) {
238
239             ccCopy.identityServices.put(e.getKey(), e.getValue().clone());
240         }
241
242         for (Entry<String, CloudSite> e : cloudSites.entrySet()) {
243
244             ccCopy.cloudSites.put(e.getKey(), e.getValue().clone());
245         }
246
247                 for (Entry<String,CloudifyManager> e:cloudifyManagers.entrySet()) {
248
249                         ccCopy.cloudifyManagers.put(e.getKey(), e.getValue().clone());
250                 }
251
252         ccCopy.configFilePath = this.configFilePath;
253         ccCopy.refreshTimerInMinutes = this.refreshTimerInMinutes;
254         ccCopy.validCloudConfig = this.validCloudConfig;
255         return ccCopy;
256     }
257
258     /* (non-Javadoc)
259      * @see java.lang.Object#hashCode()
260      */
261     @Override
262     public int hashCode() {
263         final int prime = 31;
264         int result = 1;
265         result = prime * result + ((cloudSites == null) ? 0 : cloudSites.hashCode());
266         result = prime * result + ((configFilePath == null) ? 0 : configFilePath.hashCode());
267         result = prime * result + ((identityServices == null) ? 0 : identityServices.hashCode());
268         result = prime * result + refreshTimerInMinutes;
269         result = prime * result + (validCloudConfig ? 1231 : 1237);
270         return result;
271     }
272
273     /* (non-Javadoc)
274      * @see java.lang.Object#equals(java.lang.Object)
275      */
276     @Override
277     public boolean equals(Object obj) {
278         if (this == obj)
279             return true;
280         if (obj == null)
281             return false;
282         if (getClass() != obj.getClass())
283             return false;
284         CloudConfig other = (CloudConfig) obj;
285         if (cloudSites == null) {
286             if (other.cloudSites != null)
287                 return false;
288         } else if (!cloudSites.equals(other.cloudSites))
289             return false;
290         if (configFilePath == null) {
291             if (other.configFilePath != null)
292                 return false;
293         } else if (!configFilePath.equals(other.configFilePath))
294             return false;
295         if (identityServices == null) {
296             if (other.identityServices != null)
297                 return false;
298         } else if (!identityServices.equals(other.identityServices))
299             return false;
300         if (refreshTimerInMinutes != other.refreshTimerInMinutes)
301             return false;
302         if (validCloudConfig != other.validCloudConfig)
303             return false;
304         return true;
305     }
306
307   
308 }