2 * ============LICENSE_START=======================================================
3 * ONAP : ccsdk features
4 * ================================================================================
5 * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
7 * ================================================================================
8 * Licensed under the Apache License, Version 2.0 (the "License");
9 * you may not use this file except in compliance with the License.
10 * You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing, software
15 * distributed under the License is distributed on an "AS IS" BASIS,
16 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17 * See the License for the specific language governing permissions and
18 * limitations under the License.
19 * ============LICENSE_END=========================================================
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.database;
25 import java.io.FileNotFoundException;
26 import java.io.IOException;
27 import java.nio.charset.StandardCharsets;
28 import java.nio.file.Files;
29 import java.sql.SQLException;
30 import java.text.ParseException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.List;
35 import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit;
36 import org.onap.ccsdk.features.sdnr.wt.common.database.SearchResult;
37 import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntry;
38 import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntryList;
39 import org.onap.ccsdk.features.sdnr.wt.common.database.data.DatabaseVersion;
40 import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntry;
41 import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntryList;
42 import org.onap.ccsdk.features.sdnr.wt.dataprovider.database.sqldb.SqlDBClient;
43 import org.onap.ccsdk.features.sdnr.wt.dataprovider.model.SdnrDbType;
44 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.DataMigrationProviderService;
45 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.ReleaseInformation;
46 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentData;
47 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentName;
48 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataContainer;
49 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataMigrationReport;
50 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release;
51 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ReleaseGroup;
52 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.SearchHitConverter;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
56 public class MariaDbDataMigrationProvider implements DataMigrationProviderService {
59 private static final Logger LOG = LoggerFactory.getLogger(MariaDbDataMigrationProvider.class);
60 private static final SdnrDbType DBTYPE = SdnrDbType.MARIADB;
61 private final SqlDBClient dbClient;
63 public MariaDbDataMigrationProvider(String url, String username, String password, boolean trustAll,
64 long timeoutms) throws Exception {
65 dbClient = new SqlDBClient(url, username, password);
69 public DataMigrationReport importData(String filename, boolean dryrun) throws Exception {
70 return this.importData(filename, dryrun, Release.CURRENT_RELEASE);
74 public DataMigrationReport importData(String filename, boolean dryrun, Release forRelease) throws Exception {
75 DataMigrationReport report = new DataMigrationReport();
76 File file = new File(filename);
79 report.error("file %s not found", filename);
82 throw new FileNotFoundException(filename);
84 DataContainer container = null;
86 container = DataContainer.load(file);
87 } catch (Exception e) {
89 report.error("problem loading file %s: %s", filename, e.getMessage());
92 throw new Exception("problem loading file " + filename, e);
94 ReleaseInformation ri = ReleaseInformation.getInstance(forRelease);
95 SearchHitConverter converter;
96 Set<ComponentName> components = ri.getComponents();
97 //for all db components of dest architecture
98 for (ComponentName component : components) {
99 //convert to ComponentData for current release with existing ComponentData of the container
100 converter = SearchHitConverter.Factory.getInstance(container.getRelease(), forRelease, component);
101 if (converter == null) {
104 ComponentData data = converter.convert(container);
106 String indexName = ri.getAlias(component);
107 String dataTypeName = ri.getDataType(component);
109 report.log("write %d entries into %s/%s", data.size(), indexName, dataTypeName);
111 LOG.debug("write {} entries into {}/{}", data.size(), indexName, dataTypeName);
113 for (SearchHit item : data) {
115 String id = null;//this.dbClient.doWriteRaw(indexName, dataTypeName, item.getId(), item.getSourceAsString(), true);
116 if (!item.getId().equals(id)) {
117 LOG.warn("entry for {} with original id {} was written with another id {}",
118 component.getValue(), item.getId(), id);
124 report.error("unable to convert data for " + component.getValue() + " from version "
125 + container.getRelease().getValue() + " to " + forRelease.getValue() + "\n");
127 LOG.warn("unable to convert data for {} from version {} to {}", component.getValue(),
128 container.getRelease().getValue(), forRelease.getValue());
132 LOG.info("import of {} completed", filename);
134 report.log("import of %s completed", filename);
136 report.setCompleted(true);
142 * export data if file exists .1 (.n) will be created
146 public DataMigrationReport exportData(String filename) {
147 DataMigrationReport report = new DataMigrationReport();
149 DataContainer container = new DataContainer();
151 filename = this.checkFilenameForWrite(filename);
152 LOG.info("output will be written to {}", filename);
154 Release dbRelease = this.autoDetectRelease();
155 if (dbRelease == null) {
156 report.error("unbable to detect db release. is database initialized?");
159 ReleaseInformation ri = ReleaseInformation.getInstance(dbRelease);
160 boolean componentsSucceeded = true;
161 for (ComponentName c : ri.getComponents()) {
162 ComponentData data = new ComponentData(c);
163 SearchResult<SearchHit> result = null;//this.dbClient.doReadAllJsonData(ri.getAlias(c), ri.getDataType(c), false);
164 data.addAll(result.getHits());
165 container.addComponent(c, data);
168 Files.write(new File(filename).toPath(), Arrays.asList(container.toJSON()), StandardCharsets.UTF_8);
169 report.setCompleted(componentsSucceeded);
170 } catch (IOException e) {
171 LOG.warn("problem writing data to {}: {}", filename, e);
176 private String checkFilenameForWrite(String filename) {
177 File f = new File(filename);
181 return this.checkFilenameForWrite(filename, 0);
184 private String checkFilenameForWrite(String filename, int apdx) {
185 File f = new File(String.format("$s.$d", filename, apdx));
189 return this.checkFilenameForWrite(filename, apdx + 1);
193 public Release getCurrentVersion() {
194 return Release.CURRENT_RELEASE;
199 public Release autoDetectRelease() {
200 DatabaseVersion dbVersion;
202 dbVersion = this.dbClient.readActualVersion();
203 } catch (SQLException | ParseException e) {
204 LOG.error("unable to detect db version", e);
207 AliasesEntryList aliases = this.dbClient.readViews();
208 IndicesEntryList indices = this.dbClient.readTables();
209 if (indices == null) {
212 List<Release> foundReleases = new ArrayList<>();
213 //if there are active aliases reduce indices to the active ones
214 if (aliases != null && aliases.size() > 0) {
215 indices = indices.subList(aliases.getLinkedIndices());
217 for (Release r : Release.values()) {
218 if (r.isDbInRange(dbVersion, SdnrDbType.MARIADB)) {
219 ReleaseInformation ri = ReleaseInformation.getInstance(r);
220 if (ri != null && ri.containsIndices(indices)) {
221 foundReleases.add(r);
225 if (foundReleases.size() == 1) {
226 return foundReleases.get(0);
228 LOG.error("detect {} releases: {}. unable to detect for which one to do sth.", foundReleases.size(),
234 public boolean initDatabase(Release release, int numShards, int numReplicas, String dbPrefix, boolean forceRecreate,
237 this.dbClient.waitForYellowStatus(timeoutms);
239 DatabaseVersion dbVersion;
241 dbVersion = this.dbClient.readActualVersion();
242 } catch (SQLException | ParseException e1) {
243 LOG.error("unable to detect db version", e1);
246 if (dbVersion == null) {
249 LOG.info("detected database version {}", dbVersion);
250 if (release == null) {
251 release = ReleaseGroup.CURRENT_RELEASE.getLatestCompatibleRelease(dbVersion, SdnrDbType.MARIADB);
252 if (release == null) {
253 LOG.warn("unable to autodetect release for this database version for release {}",
254 ReleaseGroup.CURRENT_RELEASE.name());
257 LOG.info("autodetect release {}", release);
259 if (!release.isDbInRange(dbVersion, SdnrDbType.MARIADB)) {
260 LOG.warn("db version {} maybe not compatible with release {}", dbVersion, release);
264 this.clearDatabase(release, dbPrefix, 0);
266 ReleaseInformation ri = ReleaseInformation.getInstance(release);
267 AliasesEntryList views = this.dbClient.readViews();
268 IndicesEntryList indices = this.dbClient.readTables();
269 if (views == null || indices == null) {
272 boolean response = false;
273 if (!ri.runPreInitCommands(this.dbClient)) {
276 for (ComponentName component : ri.getComponents()) {
278 if (ri.hasOwnDbIndex(component)) {
279 //check if index already exists
280 String tableName = ri.getIndex(component, dbPrefix);
281 String viewName = ri.getAlias(component, dbPrefix);
282 if (indices.findByIndex(tableName) == null) {
283 LOG.info("creating index for {}", component);
284 response = this.dbClient.createTable(ri.getIndex(component, dbPrefix), ri.getDatabaseMapping(component, DBTYPE));
285 LOG.info(response ? "succeeded" : "failed");
287 LOG.info("index {} for {} already exists", tableName, component);
289 //check if alias already exists
290 if (views.findByAlias(viewName) == null) {
291 LOG.info("creating alias for {}", component);
292 response = this.dbClient.createView(tableName, viewName);
293 LOG.info(response ? "succeeded" : "failed");
295 LOG.info("view {} for table {} for {} already exists", viewName, tableName, component);
298 } catch (SQLException e) {
299 LOG.error(e.getMessage());
303 if (!ri.runPostInitCommands(this.dbClient)) {
310 public boolean clearDatabase(Release release, String dbPrefix, long timeoutms) {
313 this.dbClient.waitForYellowStatus(timeoutms);
316 AliasesEntryList entries = this.dbClient.readViews();
317 IndicesEntryList entries2 = this.dbClient.readTables();
318 if (entries == null) {
321 if (release == null) {
322 DatabaseVersion dbVersion;
324 dbVersion = this.dbClient.readActualVersion();
325 } catch (SQLException | ParseException e) {
326 LOG.error("unable to detect db version", e);
329 LOG.info("detected database version {}", dbVersion);
330 release = ReleaseGroup.CURRENT_RELEASE.getLatestCompatibleRelease(dbVersion, SdnrDbType.MARIADB);
331 if (release == null) {
332 LOG.warn("unable to autodetect release for this database version for release {}",
333 ReleaseGroup.CURRENT_RELEASE.name());
336 LOG.info("autodetect release {}", release);
338 ReleaseInformation ri = ReleaseInformation.getInstance(release);
340 if (entries.size() <= 0) {
341 LOG.info("no aliases to clear");
343 //check for every component of release if alias exists
344 for (ComponentName component : ri.getComponents()) {
345 String aliasToDelete = ri.getAlias(component, dbPrefix);
346 AliasesEntry entryToDelete = entries.findByAlias(aliasToDelete);
347 if (entryToDelete != null) {
349 LOG.info("deleting alias {} for index {}", entryToDelete.getAlias(), entryToDelete.getIndex());
350 response = this.dbClient.deleteView(entryToDelete.getAlias());
351 LOG.info(response ? "succeeded" : "failed");
352 } catch (SQLException e) {
353 LOG.error(e.getMessage());
357 //try to find malformed typed index with alias name
358 IndicesEntry entry2ToDelete = entries2.findByIndex(aliasToDelete);
359 if (entry2ToDelete != null) {
361 LOG.info("deleting index {}", entry2ToDelete.getName());
362 response = this.dbClient.deleteTable(entry2ToDelete.getName());
363 LOG.info(response ? "succeeded" : "failed");
364 } catch (SQLException e) {
365 LOG.error(e.getMessage());
372 if (entries2 == null) {
375 if (entries2.size() <= 0) {
376 LOG.info("no indices to clear");
378 //check for every component of release if index exists
379 for (ComponentName component : ri.getComponents()) {
380 String indexToDelete = ri.getIndex(component, dbPrefix);
381 IndicesEntry entryToDelete = entries2.findByIndex(indexToDelete);
382 if (entryToDelete != null) {
384 LOG.info("deleting index {}", entryToDelete.getName());
385 response = this.dbClient.deleteTable(entryToDelete.getName());
386 LOG.info(response ? "succeeded" : "failed");
387 } catch (SQLException e) {
388 LOG.error(e.getMessage());
402 public boolean clearCompleteDatabase(long timeoutms) {
404 this.dbClient.waitForYellowStatus(timeoutms);
406 //check aliases and indices
407 AliasesEntryList aliases = this.dbClient.readViews();
408 IndicesEntryList indices = this.dbClient.readTables();
409 if (aliases == null || indices == null) {
412 for (AliasesEntry alias : aliases) {
414 LOG.info("deleting alias {} for index {}", alias.getAlias(), alias.getIndex());
415 this.dbClient.deleteView(alias.getAlias());
416 } catch (SQLException e) {
417 LOG.error("problem deleting alias {}: {}", alias.getAlias(), e);
421 for (IndicesEntry index : indices) {
423 LOG.info("deleting index {}", index.getName());
424 this.dbClient.deleteTable(index.getName());
425 } catch (SQLException e) {
426 LOG.error("problem deleting index {}: {}", index.getName(), e);