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;
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.text.ParseException;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.List;
34 import org.json.JSONObject;
35 import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
36 import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit;
37 import org.onap.ccsdk.features.sdnr.wt.common.database.SearchResult;
38 import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo;
39 import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntry;
40 import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntryList;
41 import org.onap.ccsdk.features.sdnr.wt.common.database.data.EsVersion;
42 import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntry;
43 import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntryList;
44 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.CreateAliasRequest;
45 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.CreateIndexRequest;
46 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteAliasRequest;
47 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteIndexRequest;
48 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.AcknowledgedResponse;
49 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.GetInfoResponse;
50 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.ListAliasesResponse;
51 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.ListIndicesResponse;
52 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentData;
53 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentName;
54 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataContainer;
55 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataMigrationReport;
56 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release;
57 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ReleaseGroup;
58 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.SearchHitConverter;
59 import org.slf4j.Logger;
60 import org.slf4j.LoggerFactory;
62 public class DataMigrationProviderImpl implements DataMigrationProviderService {
65 private static final Logger LOG = LoggerFactory.getLogger(DataMigrationProviderImpl.class);
67 private final HtDatabaseClient dbClient;
69 public DataMigrationProviderImpl(HostInfo[] hosts, String username, String password, boolean trustAll,
70 long timeoutms) throws Exception {
72 dbClient = HtDatabaseClient.getClient(hosts, username, password, trustAll, timeoutms);
76 public DataMigrationReport importData(String filename, boolean dryrun) throws Exception {
77 return this.importData(filename, dryrun, Release.CURRENT_RELEASE);
80 public DataMigrationReport importData(String filename, boolean dryrun, Release forRelease) throws Exception {
81 DataMigrationReport report = new DataMigrationReport();
82 File file = new File(filename);
85 report.error("file %s not found", filename);
88 throw new FileNotFoundException(filename);
90 DataContainer container = null;
92 container = DataContainer.load(file);
93 } catch (Exception e) {
95 report.error("problem loading file %s: %s", filename, e.getMessage());
98 throw new Exception("problem loading file " + filename, e);
100 ReleaseInformation ri = ReleaseInformation.getInstance(forRelease);
101 SearchHitConverter converter;
102 Set<ComponentName> components = ri.getComponents();
103 //for all db components of dest architecture
104 for (ComponentName component : components) {
105 //convert to ComponentData for current release with existing ComponentData of the container
106 converter = SearchHitConverter.Factory.getInstance(container.getRelease(), forRelease, component);
107 if (converter == null) {
110 ComponentData data = converter.convert(container);
112 String indexName = ri.getAlias(component);
113 String dataTypeName = ri.getDataType(component);
115 report.log("write %d entries into %s/%s", data.size(), indexName, dataTypeName);
117 LOG.debug("write {} entries into {}/{}", data.size(), indexName, dataTypeName);
119 for (SearchHit item : data) {
121 String id = this.dbClient.doWriteRaw(indexName, dataTypeName, item.getId(),
122 item.getSourceAsString(), true);
123 if (!item.getId().equals(id)) {
124 LOG.warn("entry for {} with original id {} was written with another id {}",
125 component.getValue(), item.getId(), id);
131 report.error("unable to convert data for " + component.getValue() + " from version "
132 + container.getRelease().getValue() + " to " + forRelease.getValue() + "\n");
134 LOG.warn("unable to convert data for {} from version {} to {}", component.getValue(),
135 container.getRelease().getValue(), forRelease.getValue());
139 LOG.info("import of {} completed", filename);
141 report.log("import of %s completed", filename);
143 report.setCompleted(true);
149 * export data if file exists .1 (.n) will be created
153 public DataMigrationReport exportData(String filename) {
154 DataMigrationReport report = new DataMigrationReport();
156 DataContainer container = new DataContainer();
158 filename = this.checkFilenameForWrite(filename);
159 LOG.info("output will be written to {}", filename);
161 Release dbRelease = this.autoDetectRelease();
162 if (dbRelease == null) {
163 report.error("unbable to detect db release. is database initialized?");
166 ReleaseInformation ri = ReleaseInformation.getInstance(dbRelease);
167 boolean componentsSucceeded = true;
168 for (ComponentName c : ri.getComponents()) {
169 ComponentData data = new ComponentData(c);
170 SearchResult<SearchHit> result = this.dbClient.doReadAllJsonData(ri.getAlias(c), ri.getDataType(c), false);
171 data.addAll(result.getHits());
172 container.addComponent(c, data);
175 Files.write(new File(filename).toPath(), Arrays.asList(container.toJSON()), StandardCharsets.UTF_8);
176 report.setCompleted(componentsSucceeded);
177 } catch (IOException e) {
178 LOG.warn("problem writing data to {}: {}", filename, e);
183 private String checkFilenameForWrite(String filename) {
184 File f = new File(filename);
188 return this.checkFilenameForWrite(filename, 0);
191 private String checkFilenameForWrite(String filename, int apdx) {
192 File f = new File(String.format("$s.$d", filename, apdx));
196 return this.checkFilenameForWrite(filename, apdx + 1);
200 public Release getCurrentVersion() {
201 return Release.CURRENT_RELEASE;
205 public Release autoDetectRelease() {
206 EsVersion dbVersion = this.readActualVersion();
207 AliasesEntryList aliases = this.readAliases();
208 IndicesEntryList indices = this.readIndices();
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)) {
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(),
233 private EsVersion readActualVersion() {
235 GetInfoResponse response = this.dbClient.getInfo();
236 return response.getVersion();
237 } catch (Exception e) {
238 LOG.warn(e.getMessage());
243 private AliasesEntryList readAliases() {
244 AliasesEntryList entries = null;
246 ListAliasesResponse response = this.dbClient.getAliases();
247 entries = response.getEntries();
248 } catch (ParseException | IOException e) {
249 LOG.error(e.getMessage());
254 private IndicesEntryList readIndices() {
255 IndicesEntryList entries = null;
257 ListIndicesResponse response = this.dbClient.getIndices();
258 entries = response.getEntries();
259 } catch (ParseException | IOException e) {
260 LOG.error(e.getMessage());
267 public boolean initDatabase(Release release, int numShards, int numReplicas, String dbPrefix, boolean forceRecreate,
270 this.dbClient.waitForYellowStatus(timeoutms);
272 EsVersion dbVersion = this.readActualVersion();
273 if (dbVersion == null) {
276 LOG.info("detected database version {}", dbVersion);
277 if (release == null) {
278 release = ReleaseGroup.CURRENT_RELEASE.getLatestCompatibleRelease(dbVersion);
279 if (release == null) {
280 LOG.warn("unable to autodetect release for this database version for release {}",
281 ReleaseGroup.CURRENT_RELEASE.name());
284 LOG.info("autodetect release {}", release);
286 if (!release.isDbInRange(dbVersion)) {
287 LOG.warn("db version {} maybe not compatible with release {}", dbVersion, release);
291 this.clearDatabase(release, dbPrefix, 0);
293 ReleaseInformation ri = ReleaseInformation.getInstance(release);
294 AliasesEntryList aliases = this.readAliases();
295 IndicesEntryList indices = this.readIndices();
296 if (aliases == null || indices == null) {
299 AcknowledgedResponse response = null;
300 if (!ri.runPreInitCommands(this.dbClient)) {
303 for (ComponentName component : ri.getComponents()) {
305 if (ri.hasOwnDbIndex(component)) {
306 //check if index already exists
307 String indexName = ri.getIndex(component, dbPrefix);
308 String aliasName = ri.getAlias(component, dbPrefix);
309 if (indices.findByIndex(indexName) == null) {
310 LOG.info("creating index for {}", component);
311 CreateIndexRequest request = new CreateIndexRequest(ri.getIndex(component, dbPrefix));
312 request.mappings(new JSONObject(ri.getDatabaseMapping(component)));
313 request.settings(new JSONObject(ri.getDatabaseSettings(component, numShards, numReplicas)));
314 response = this.dbClient.createIndex(request);
315 LOG.info(response.isAcknowledged() ? "succeeded" : "failed");
317 LOG.info("index {} for {} already exists", indexName, component);
319 //check if alias already exists
320 if (aliases.findByAlias(aliasName) == null) {
321 LOG.info("creating alias for {}", component);
322 response = this.dbClient.createAlias(new CreateAliasRequest(indexName, aliasName));
323 LOG.info(response.isAcknowledged() ? "succeeded" : "failed");
325 LOG.info("alias {} for index {} for {} already exists", aliasName, indexName, component);
328 } catch (IOException e) {
329 LOG.error(e.getMessage());
333 if (!ri.runPostInitCommands(this.dbClient)) {
340 public boolean clearDatabase(Release release, String dbPrefix, long timeoutms) {
343 this.dbClient.waitForYellowStatus(timeoutms);
346 AliasesEntryList entries = this.readAliases();
347 IndicesEntryList entries2 = this.readIndices();
348 if (entries == null) {
351 if (release == null) {
352 EsVersion dbVersion = this.readActualVersion();
353 if (dbVersion == null) {
356 LOG.info("detected database version {}", dbVersion);
357 release = ReleaseGroup.CURRENT_RELEASE.getLatestCompatibleRelease(dbVersion);
358 if (release == null) {
359 LOG.warn("unable to autodetect release for this database version for release {}",
360 ReleaseGroup.CURRENT_RELEASE.name());
363 LOG.info("autodetect release {}", release);
365 ReleaseInformation ri = ReleaseInformation.getInstance(release);
366 AcknowledgedResponse response;
367 if (entries.size() <= 0) {
368 LOG.info("no aliases to clear");
370 //check for every component of release if alias exists
371 for (ComponentName component : ri.getComponents()) {
372 String aliasToDelete = ri.getAlias(component, dbPrefix);
373 AliasesEntry entryToDelete = entries.findByAlias(aliasToDelete);
374 if (entryToDelete != null) {
376 LOG.info("deleting alias {} for index {}", entryToDelete.getAlias(), entryToDelete.getIndex());
377 response = this.dbClient.deleteAlias(
378 new DeleteAliasRequest(entryToDelete.getIndex(), entryToDelete.getAlias()));
379 LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed");
380 } catch (IOException e) {
381 LOG.error(e.getMessage());
386 //try to find malformed typed index with alias name
387 IndicesEntry entry2ToDelete = entries2.findByIndex(aliasToDelete);
388 if (entry2ToDelete != null) {
390 LOG.info("deleting index {}", entry2ToDelete.getName());
391 response = this.dbClient.deleteIndex(new DeleteIndexRequest(entry2ToDelete.getName()));
392 LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed");
393 } catch (IOException e) {
394 LOG.error(e.getMessage());
401 if (entries2 == null) {
404 if (entries2.size() <= 0) {
405 LOG.info("no indices to clear");
407 //check for every component of release if index exists
408 for (ComponentName component : ri.getComponents()) {
409 String indexToDelete = ri.getIndex(component, dbPrefix);
410 IndicesEntry entryToDelete = entries2.findByIndex(indexToDelete);
411 if (entryToDelete != null) {
413 LOG.info("deleting index {}", entryToDelete.getName());
414 response = this.dbClient.deleteIndex(new DeleteIndexRequest(entryToDelete.getName()));
415 LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed");
416 } catch (IOException e) {
417 LOG.error(e.getMessage());
431 public boolean clearCompleteDatabase(long timeoutms) {
433 this.dbClient.waitForYellowStatus(timeoutms);
435 //check aliases and indices
436 AliasesEntryList aliases = this.readAliases();
437 IndicesEntryList indices = this.readIndices();
438 if (aliases == null || indices == null) {
441 for (AliasesEntry alias : aliases) {
443 LOG.info("deleting alias {} for index {}", alias.getAlias(), alias.getIndex());
444 this.dbClient.deleteAlias(new DeleteAliasRequest(alias.getIndex(), alias.getAlias()));
445 } catch (IOException e) {
446 LOG.error("problem deleting alias {}: {}", alias.getAlias(), e);
450 for (IndicesEntry index : indices) {
452 LOG.info("deleting index {}", index.getName());
453 this.dbClient.deleteIndex(new DeleteIndexRequest(index.getName()));
454 } catch (IOException e) {
455 LOG.error("problem deleting index {}: {}", index.getName(), e);