Springboot 2.0 upgrade
[so.git] / adapters / mso-openstack-adapters / src / main / java / db / migration / R__CloudConfigMigration.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 - 2018 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 db.migration;
22
23 import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
24 import com.fasterxml.jackson.annotation.JsonProperty;
25 import com.fasterxml.jackson.databind.ObjectMapper;
26 import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
27 import org.flywaydb.core.api.MigrationVersion;
28 import org.flywaydb.core.api.migration.MigrationChecksumProvider;
29 import org.flywaydb.core.api.migration.MigrationInfoProvider;
30 import org.flywaydb.core.api.migration.jdbc.JdbcMigration;
31 import org.onap.so.db.catalog.beans.CloudIdentity;
32 import org.onap.so.db.catalog.beans.CloudSite;
33 import org.onap.so.db.catalog.beans.CloudifyManager;
34 import org.onap.so.logger.MsoLogger;
35
36 import java.io.FileInputStream;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.sql.Connection;
40 import java.sql.PreparedStatement;
41 import java.sql.ResultSet;
42 import java.sql.SQLException;
43 import java.sql.Statement;
44 import java.util.Collection;
45
46 /**
47  * Performs migration using JDBC Connection from the cloud config provided in the environment (application-{profile}.yaml) and persist data (when not already present) to the catalod database.
48  */
49 @JsonIgnoreProperties(ignoreUnknown = true)
50 public class R__CloudConfigMigration implements JdbcMigration , MigrationInfoProvider, MigrationChecksumProvider {
51     public static final String FLYWAY = "FLYWAY";
52
53     private static final MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, R__CloudConfigMigration.class);
54     @JsonProperty("cloud_config")
55     private CloudConfig cloudConfig;
56     
57     @Override
58     public boolean isUndo(){
59         return false;
60     }
61
62     @Override
63     public void migrate(Connection connection) throws Exception {
64         LOGGER.debug("Starting migration for CloudConfig");
65         
66         CloudConfig cloudConfig = null;
67
68         // Try the override file
69         String configLocation = System.getProperty("spring.config.location");
70         if (configLocation != null) {
71             try (InputStream stream = new FileInputStream(configLocation)) {
72                 cloudConfig = loadCloudConfig(stream);
73             }
74         }
75         
76         if (cloudConfig == null) {
77                 LOGGER.debug("No CloudConfig defined in " + configLocation);
78
79                 // Try the application.yaml file
80             try (InputStream stream = R__CloudConfigMigration.class.getResourceAsStream(getApplicationYamlName())) {
81                 cloudConfig = loadCloudConfig(stream);
82             }
83
84             if (cloudConfig == null) {
85                 LOGGER.debug("No CloudConfig defined in " + getApplicationYamlName());
86             }
87         }
88  
89         if(cloudConfig != null){
90             migrateCloudIdentity(cloudConfig.getIdentityServices().values(), connection);
91             migrateCloudSite(cloudConfig.getCloudSites().values(), connection);
92             migrateCloudifyManagers(cloudConfig.getCloudifyManagers().values(), connection);
93         }
94     }
95
96     public CloudConfig getCloudConfig() {
97         return cloudConfig;
98     }
99
100     public void setCloudConfig(CloudConfig cloudConfig) {
101         this.cloudConfig = cloudConfig;
102     }
103
104     private CloudConfig loadCloudConfig(InputStream stream) throws IOException  {
105         ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
106         R__CloudConfigMigration cloudConfigMigration =
107                         mapper.readValue(stream, R__CloudConfigMigration.class);
108         CloudConfig cloudConfig = cloudConfigMigration.getCloudConfig();
109
110         if(cloudConfig != null){
111                 cloudConfig.populateId();
112         }
113
114         return cloudConfig;
115     }
116
117     private String getApplicationYamlName() {
118         String profile = System.getProperty("spring.profiles.active") == null ? "" : "-" + System.getProperty("spring.profiles.active");
119         return "/application" + profile + ".yaml";
120     }
121
122     private void migrateCloudIdentity(Collection<CloudIdentity> entities, Connection connection) throws SQLException  {
123         LOGGER.debug("Starting migration for CloudConfig-->IdentityService");
124         String insert = "INSERT INTO `identity_services` (`ID`, `IDENTITY_URL`, `MSO_ID`, `MSO_PASS`, `ADMIN_TENANT`, `MEMBER_ROLE`, `TENANT_METADATA`, `IDENTITY_SERVER_TYPE`, `IDENTITY_AUTHENTICATION_TYPE`, `LAST_UPDATED_BY`) " +
125                 "VALUES (?,?,?,?,?,?,?,?,?,?);";
126
127         try (Statement stmt = connection.createStatement();PreparedStatement ps = connection.prepareStatement(insert)) {
128             for (CloudIdentity cloudIdentity : entities) {
129                 try (ResultSet rows = stmt.executeQuery("Select count(1) from identity_services where id='" + cloudIdentity.getId() + "'")) {
130                     int count = 0;
131                     while (rows.next()) {
132                         count = rows.getInt(1);
133                     }
134                     if (count == 0) {
135                         ps.setString(1, cloudIdentity.getId());
136                         ps.setString(2, cloudIdentity.getIdentityUrl());
137                         ps.setString(3, cloudIdentity.getMsoId());
138                         ps.setString(4, cloudIdentity.getMsoPass());
139                         ps.setString(5, cloudIdentity.getAdminTenant());
140                         ps.setString(6, cloudIdentity.getMemberRole());
141                         ps.setBoolean(7, cloudIdentity.getTenantMetadata());
142                         ps.setString(8, cloudIdentity.getIdentityServerType() != null ? cloudIdentity.getIdentityServerType().name() : null);
143                         ps.setString(9, cloudIdentity.getIdentityAuthenticationType() != null ? cloudIdentity.getIdentityAuthenticationType().name() : null);
144                         ps.setString(10, FLYWAY);
145                         ps.executeUpdate();
146                     }
147                 }
148             }
149         }
150     }
151
152     private void migrateCloudSite(Collection<CloudSite> entities, Connection connection) throws SQLException  {
153         LOGGER.debug("Starting migration for CloudConfig-->CloudSite");
154         String insert = "INSERT INTO `cloud_sites` (`ID`, `REGION_ID`, `IDENTITY_SERVICE_ID`, `CLOUD_VERSION`, `CLLI`, `CLOUDIFY_ID`, `PLATFORM`, `ORCHESTRATOR`, `LAST_UPDATED_BY`) " +
155                 "VALUES (?,?,?,?,?,?,?,?,?);";
156
157         try (Statement stmt = connection.createStatement();PreparedStatement ps = connection.prepareStatement(insert)) {
158             for (CloudSite cloudSite : entities) {
159                 try (ResultSet rows = stmt.executeQuery("Select count(1) from cloud_sites where id='" + cloudSite.getId() + "'")) {
160                     int count = 0;
161                     while (rows.next()) {
162                         count = rows.getInt(1);
163                     }
164                     if (count == 0) {
165                         ps.setString(1, cloudSite.getId());
166                         ps.setString(2, cloudSite.getRegionId());
167                         ps.setString(3, cloudSite.getIdentityServiceId());
168                         ps.setString(4, cloudSite.getCloudVersion());
169                         ps.setString(5, cloudSite.getClli());
170                         ps.setString(6, cloudSite.getCloudifyId());
171                         ps.setString(7, cloudSite.getPlatform());
172                         ps.setString(8, cloudSite.getOrchestrator());
173                         ps.setString(9, FLYWAY);
174                         ps.executeUpdate();
175                     }
176                 }
177             }
178         }
179     }
180
181     private void migrateCloudifyManagers(Collection<CloudifyManager> entities, Connection connection) throws SQLException  {
182         String insert = "INSERT INTO `cloudify_managers` (`ID`, `CLOUDIFY_URL`, `USERNAME`, `PASSWORD`, `VERSION`, `LAST_UPDATED_BY`)" +
183                 " VALUES (?,?,?,?,?,?);";
184
185         try (Statement stmt = connection.createStatement();PreparedStatement ps = connection.prepareStatement(insert)) {
186             for (CloudifyManager cloudifyManager : entities) {
187                 try (ResultSet rows = stmt.executeQuery("Select count(1) from cloudify_managers where id='" + cloudifyManager.getId() + "'")) {
188                     int count = 0;
189                     while (rows.next()) {
190                         count = rows.getInt(1);
191                     }
192                     if (count == 0) {
193                         ps.setString(1, cloudifyManager.getId());
194                         ps.setString(2, cloudifyManager.getCloudifyUrl());
195                         ps.setString(3, cloudifyManager.getUsername());
196                         ps.setString(4, cloudifyManager.getPassword());
197                         ps.setString(5, cloudifyManager.getVersion());
198                         ps.setString(6, FLYWAY);
199                         ps.executeUpdate();
200                     }
201                 }
202             }
203         }
204     }
205
206     public MigrationVersion getVersion() {
207         return null;
208     }
209
210     public String getDescription() {
211         return "R_CloudConfigMigration";
212     }
213
214     public Integer getChecksum() {
215         return Math.toIntExact(System.currentTimeMillis() / 1000);
216     }
217 }
218