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;
35 import org.json.JSONObject;
36 import org.onap.ccsdk.features.sdnr.wt.common.database.HtDatabaseClient;
37 import org.onap.ccsdk.features.sdnr.wt.common.database.Portstatus;
38 import org.onap.ccsdk.features.sdnr.wt.common.database.SearchHit;
39 import org.onap.ccsdk.features.sdnr.wt.common.database.SearchResult;
40 import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo;
41 import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntry;
42 import org.onap.ccsdk.features.sdnr.wt.common.database.data.AliasesEntryList;
43 import org.onap.ccsdk.features.sdnr.wt.common.database.data.EsVersion;
44 import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntry;
45 import org.onap.ccsdk.features.sdnr.wt.common.database.data.IndicesEntryList;
46 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.CreateAliasRequest;
47 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.CreateIndexRequest;
48 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteAliasRequest;
49 import org.onap.ccsdk.features.sdnr.wt.common.database.requests.DeleteIndexRequest;
50 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.AcknowledgedResponse;
51 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.GetInfoResponse;
52 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.ListAliasesResponse;
53 import org.onap.ccsdk.features.sdnr.wt.common.database.responses.ListIndicesResponse;
54 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentData;
55 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.ComponentName;
56 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataMigrationReport;
57 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataContainer;
58 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release;
59 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.SearchHitConverter;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
63 public class DataMigrationProviderImpl implements DataMigrationProviderService {
66 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,
73 Portstatus.waitSecondsTillAvailable(timeoutms / 1000, hosts);
75 this.dbClient = new HtDatabaseClient(hosts, username, password, trustAll);
79 public DataMigrationReport importData(String filename, boolean dryrun) throws Exception {
80 return this.importData(filename, dryrun, Release.CURRENT_RELEASE);
83 public DataMigrationReport importData(String filename, boolean dryrun, Release forRelease) throws Exception {
84 DataMigrationReport report = new DataMigrationReport();
85 File file = new File(filename);
88 report.error("file %s not found", filename);
91 throw new FileNotFoundException(filename);
93 DataContainer container = null;
95 container = DataContainer.load(file);
96 } catch (Exception e) {
98 report.error("problem loading file %s: %s", filename, e.getMessage());
101 throw new Exception("problem loading file " + filename, e);
103 ReleaseInformation ri = ReleaseInformation.getInstance(forRelease);
104 SearchHitConverter converter;
105 Set<ComponentName> components = ri.getComponents();
106 //for all db components of dest architecture
107 for (ComponentName component : components) {
108 //convert to ComponentData for current release with existing ComponentData of the container
109 converter = SearchHitConverter.Factory.getInstance(container.getRelease(), forRelease, component);
110 if (converter == null) {
113 ComponentData data = converter.convert(container);
115 String indexName = ri.getAlias(component);
116 String dataTypeName = ri.getDataType(component);
118 report.log("write %d entries into %s/%s", data.size(), indexName, dataTypeName);
120 LOG.debug("write {} entries into {}/{}", data.size(), indexName, dataTypeName);
122 for (SearchHit item : data) {
124 String id = this.dbClient.doWriteRaw(indexName, dataTypeName, item.getId(),
125 item.getSourceAsString());
126 if (!item.getId().equals(id)) {
127 LOG.warn("entry for {} with original id {} was written with another id {}",
128 component.getValue(), item.getId(), id);
134 report.error("unable to convert data for " + component.getValue() + " from version "
135 + container.getRelease().getValue() + " to " + forRelease.getValue() + "\n");
137 LOG.warn("unable to convert data for {} from version {} to {}", component.getValue(),
138 container.getRelease().getValue(), forRelease.getValue());
142 LOG.info("import of {} completed", filename);
144 report.log("import of %s completed", filename);
146 report.setCompleted(true);
152 * export data if file exists .1 (.n) will be created
156 public DataMigrationReport exportData(String filename) {
157 DataMigrationReport report = new DataMigrationReport();
159 DataContainer container = new DataContainer();
161 filename = this.checkFilenameForWrite(filename);
162 LOG.info("output will be written to {}", filename);
164 Release dbRelease = this.autoDetectRelease();
165 if (dbRelease == null) {
166 report.error("unbable to detect db release. is database initialized?");
169 ReleaseInformation ri = ReleaseInformation.getInstance(dbRelease);
170 boolean componentsSucceeded = true;
171 for (ComponentName c : ri.getComponents()) {
172 ComponentData data = new ComponentData(c);
173 SearchResult<SearchHit> result = this.dbClient.doReadAllJsonData(ri.getAlias(c), ri.getDataType(c), false);
174 data.addAll(result.getHits());
175 container.addComponent(c, data);
178 Files.write(new File(filename).toPath(), Arrays.asList(container.toJSON()), StandardCharsets.UTF_8);
179 report.setCompleted(componentsSucceeded);
180 } catch (IOException e) {
181 LOG.warn("problem writing data to {}: {}", filename, e);
186 private String checkFilenameForWrite(String filename) {
187 File f = new File(filename);
191 return this.checkFilenameForWrite(filename, 0);
194 private String checkFilenameForWrite(String filename, int apdx) {
195 File f = new File(String.format("$s.$d", filename, apdx));
199 return this.checkFilenameForWrite(filename, apdx + 1);
203 public Release getCurrentVersion() {
204 return Release.CURRENT_RELEASE;
208 public Release autoDetectRelease() {
209 EsVersion dbVersion = this.readActualVersion();
210 AliasesEntryList aliases = this.readAliases();
211 IndicesEntryList indices = this.readIndices();
212 if (indices == null) {
215 List<Release> foundReleases = new ArrayList<>();
216 //if there are active aliases reduce indices to the active ones
217 if (aliases != null && aliases.size() > 0) {
218 indices = indices.subList(aliases.getLinkedIndices());
220 for (Release r : Release.values()) {
221 if (r.isDbInRange(dbVersion)) {
222 ReleaseInformation ri = ReleaseInformation.getInstance(r);
223 if (ri != null && ri.containsIndices(indices)) {
224 foundReleases.add(r);
228 if (foundReleases.size() == 1) {
229 return foundReleases.get(0);
231 LOG.error("detect {} releases: {}. unable to detect for which one to do sth.", foundReleases.size(),
236 private EsVersion readActualVersion() {
238 GetInfoResponse response = this.dbClient.getInfo();
239 return response.getVersion();
240 } catch (Exception e) {
241 LOG.warn(e.getMessage());
246 private AliasesEntryList readAliases() {
247 AliasesEntryList entries = null;
249 ListAliasesResponse response = this.dbClient.getAliases();
250 entries = response.getEntries();
251 } catch (ParseException | IOException e) {
252 LOG.error(e.getMessage());
257 private IndicesEntryList readIndices() {
258 IndicesEntryList entries = null;
260 ListIndicesResponse response = this.dbClient.getIndices();
261 entries = response.getEntries();
262 } catch (ParseException | IOException e) {
263 LOG.error(e.getMessage());
269 public boolean initDatabase(Release release, int numShards, int numReplicas, String dbPrefix, boolean forceRecreate,
272 this.dbClient.waitForYellowStatus(timeoutms);
274 EsVersion dbVersion = this.readActualVersion();
275 if (dbVersion == null) {
278 if (!release.isDbInRange(dbVersion)) {
279 LOG.warn("db version {} maybe not compatible with release {}", dbVersion, release);
283 this.clearDatabase(release, dbPrefix, 0);
285 ReleaseInformation ri = ReleaseInformation.getInstance(release);
286 AliasesEntryList aliases = this.readAliases();
287 IndicesEntryList indices = this.readIndices();
288 if (aliases == null || indices == null) {
291 AcknowledgedResponse response = null;
292 if (!ri.runPreInitCommands(this.dbClient)) {
295 for (ComponentName component : ri.getComponents()) {
297 if (ri.hasOwnDbIndex(component)) {
298 //check if index already exists
299 String indexName = ri.getIndex(component, dbPrefix);
300 String aliasName = ri.getAlias(component, dbPrefix);
301 if (indices.findByIndex(indexName) == null) {
302 LOG.info("creating index for {}", component);
303 CreateIndexRequest request = new CreateIndexRequest(ri.getIndex(component, dbPrefix));
304 request.mappings(new JSONObject(ri.getDatabaseMapping(component)));
305 request.settings(new JSONObject(ri.getDatabaseSettings(component, numShards, numReplicas)));
306 response = this.dbClient.createIndex(request);
307 LOG.info(response.isAcknowledged() ? "succeeded" : "failed");
309 LOG.info("index {} for {} already exists", indexName, component);
311 //check if alias already exists
312 if (aliases.findByAlias(aliasName) == null) {
313 LOG.info("creating alias for {}", component);
314 response = this.dbClient.createAlias(new CreateAliasRequest(indexName, aliasName));
315 LOG.info(response.isAcknowledged() ? "succeeded" : "failed");
317 LOG.info("alias {} for index {} for {} already exists", aliasName, indexName, component);
320 } catch (IOException e) {
321 LOG.error(e.getMessage());
325 if (!ri.runPostInitCommands(this.dbClient)) {
332 public boolean clearDatabase(Release release, String dbPrefix, long timeoutms) {
335 this.dbClient.waitForYellowStatus(timeoutms);
338 AliasesEntryList entries = this.readAliases();
339 if (entries == null) {
342 ReleaseInformation ri = ReleaseInformation.getInstance(release);
343 AcknowledgedResponse response;
344 if (entries.size() <= 0) {
345 LOG.info("no aliases to clear");
347 //check for every component of release if alias exists
348 for (ComponentName component : ri.getComponents()) {
349 String aliasToDelete = ri.getAlias(component, dbPrefix);
350 AliasesEntry entryToDelete = entries.findByAlias(aliasToDelete);
351 if (entryToDelete != null) {
353 LOG.info("deleting alias {} for index {}", entryToDelete.getAlias(), entryToDelete.getIndex());
354 response = this.dbClient.deleteAlias(
355 new DeleteAliasRequest(entryToDelete.getIndex(), entryToDelete.getAlias()));
356 LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed");
357 } catch (IOException e) {
358 LOG.error(e.getMessage());
364 IndicesEntryList entries2 = this.readIndices();
365 if (entries2 == null) {
368 if (entries2.size() <= 0) {
369 LOG.info("no indices to clear");
371 //check for every component of release if index exists
372 for (ComponentName component : ri.getComponents()) {
373 String indexToDelete = ri.getIndex(component, dbPrefix);
374 IndicesEntry entryToDelete = entries2.findByIndex(indexToDelete);
375 if (entryToDelete != null) {
377 LOG.info("deleting index {}", entryToDelete.getName());
378 response = this.dbClient.deleteIndex(new DeleteIndexRequest(entryToDelete.getName()));
379 LOG.info(response.isResponseSucceeded() ? "succeeded" : "failed");
380 } catch (IOException e) {
381 LOG.error(e.getMessage());
395 public boolean clearCompleteDatabase(long timeoutms) {
397 this.dbClient.waitForYellowStatus(timeoutms);
399 //check aliases and indices
400 AliasesEntryList aliases = this.readAliases();
401 IndicesEntryList indices = this.readIndices();
402 if (aliases == null || indices == null) {
405 for (AliasesEntry alias : aliases) {
407 LOG.info("deleting alias {} for index {}", alias.getAlias(), alias.getIndex());
408 this.dbClient.deleteAlias(new DeleteAliasRequest(alias.getIndex(), alias.getAlias()));
409 } catch (IOException e) {
410 LOG.error("problem deleting alias {}: {}", alias.getAlias(), e);
414 for (IndicesEntry index : indices) {
416 LOG.info("deleting index {}", index.getName());
417 this.dbClient.deleteIndex(new DeleteIndexRequest(index.getName()));
418 } catch (IOException e) {
419 LOG.error("problem deleting index {}: {}", index.getName(), e);