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