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;
24 import java.util.Arrays;
25 import java.util.List;
27 import org.apache.commons.cli.*;
28 import org.apache.commons.logging.Log;
29 import org.apache.commons.logging.LogFactory;
30 import org.apache.log4j.ConsoleAppender;
31 import org.apache.log4j.Level;
32 import org.apache.log4j.Logger;
33 import org.apache.log4j.PatternLayout;
34 import org.apache.log4j.RollingFileAppender;
35 import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo;
36 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataMigrationReport;
37 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.MavenDatabasePluginInitFile;
38 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release;
41 * @author Michael Dürre
44 public class Program {
47 private static final String CMD_INITDB = "init";
48 private static final String CMD_CLEAR_DB = "delete";
49 private static final String CMD_CLEAR_DB_COMPLETE = "clear";
50 private static final String CMD_CREATE_PLUGIN_INIT_FILE = "pluginfile";
51 private static final String CMD_IMPORT = "import";
52 private static final String CMD_EXPORT = "export";
53 private static final String CMD_LIST_VERSION = "list";
55 private static final String CMD_INITDB_DESCRIPTION = "initialize databse indices and aliases";
56 private static final String CMD_CLEAR_DB_DESCRIPTION = "clear database indices and aliases";
57 private static final String CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION = "create maven plugin file";
58 private static final String CMD_IMPORT_DESCRIPTION = "import data into database";
59 private static final String CMD_EXPORT_DESCRIPTION = "export data from database";
60 private static final String CMD_LIST_VERSION_DESCRIPTION = "list release versions";
62 private static final List<String[]> commands = Arrays.asList(new String[] { CMD_INITDB, CMD_INITDB_DESCRIPTION },
63 new String[] { CMD_CLEAR_DB, CMD_CLEAR_DB_DESCRIPTION },
64 new String[] { CMD_CREATE_PLUGIN_INIT_FILE, CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION },
65 new String[] { CMD_IMPORT, CMD_IMPORT_DESCRIPTION }, new String[] { CMD_EXPORT, CMD_EXPORT_DESCRIPTION },
66 new String[] { CMD_LIST_VERSION, CMD_LIST_VERSION_DESCRIPTION });
67 private static final String APPLICATION_NAME = "SDNR DataMigrationTool";
68 private static final int DEFAULT_SHARDS = 5;
69 private static final int DEFAULT_REPLICAS = 1;
70 private static final String DEFAULT_DBURL = "http://sdnrdb:9200";
71 private static final String DEFAULT_DBPREFIX = "";
72 private static final String OPTION_FORCE_RECREATE_SHORT = "f";
73 private static final String OPTION_SILENT_SHORT = "n";
74 private static final String OPTION_SILENT = "silent";
75 private static final String OPTION_VERSION_SHORT = "v";
76 private static final String OPTION_SHARDS_SHORT = "s";
77 private static final String OPTION_REPLICAS_SHORT = "r";
78 private static final String OPTION_OUTPUTFILE_SHORT = "of";
79 private static final String OPTION_INPUTFILE_SHORT = "if";
80 private static final String OPTION_DEBUG_SHORT = "x";
81 private static final String OPTION_TRUSTINSECURESSL_SHORT = "k";
82 private static final String OPTION_DATABASE_SHORT = "db";
83 private static final String OPTION_COMMAND_SHORT = "c";
84 private static final String OPTION_DATABASEUSER_SHORT = "dbu";
85 private static final String OPTION_DATABASEPASSWORD_SHORT = "dbp";
86 private static final String OPTION_DATABASEPREFIX_SHORT = "p";
87 private static final String OPTION_DATABASEWAIT_SHORT = "w";
88 private static final String OPTION_HELP_SHORT = "h";
92 private static Options options = init();
93 private static Log LOG = null;
97 public static void main(String[] args) {
98 System.exit( main2(args) );
100 // end of public methods
103 @SuppressWarnings("unchecked")
104 private static <T> T getOptionOrDefault(CommandLine cmd, String option, T def) throws ParseException {
105 if (def instanceof Boolean) {
106 return cmd.hasOption(option) ? (T) Boolean.TRUE : def;
108 if (def instanceof Integer) {
109 return cmd.hasOption(option) ? (T) Integer.valueOf(cmd.getOptionValue(option)) : def;
111 if (def instanceof Long) {
112 return cmd.hasOption(option) ? (T) Long.valueOf(cmd.getOptionValue(option)) : def;
114 if (cmd.hasOption(option) && cmd.getOptionValue(option) != null) {
115 if (option.equals(OPTION_VERSION_SHORT)) {
116 String v = cmd.getOptionValue(option);
117 return (T) Release.getValueBySuffix(v.startsWith("-") ? v : "-" + v);
119 return (T) cmd.getParsedOptionValue(option);
125 private static void initLog(boolean silent, String logfile, Level loglvl) {
126 Logger.getRootLogger().getLoggerRepository().resetConfiguration();
127 LOG = LogFactory.getLog(Program.class);
129 ConsoleAppender console = new ConsoleAppender(); // create appender
130 // configure the appender
131 String PATTERN = "%d [%p|%C{1}] %m%n";
132 console.setLayout(new PatternLayout(PATTERN));
133 console.setThreshold(loglvl);
134 console.activateOptions();
135 // add appender to any Logger (here is root)
136 Logger.getRootLogger().addAppender(console);
138 if (logfile != null) {
139 RollingFileAppender fa = new RollingFileAppender();
140 fa.setName("FileLogger");
142 fa.setLayout(new PatternLayout("%d %-5p [%c] %m%n"));
143 fa.setThreshold(loglvl);
144 fa.setMaximumFileSize(10000000);
146 fa.setMaxBackupIndex(5);
147 fa.activateOptions();
148 // add appender to any Logger (here is root)
149 Logger.getRootLogger().addAppender(fa);
151 // repeat with all other desired appenders
154 private static int main2(String[] args) {
156 CommandLineParser parser = new DefaultParser();
157 HelpFormatter formatter = new HelpFormatter();
158 CommandLine cmd = null;
161 cmd = parser.parse(options, args);
162 } catch (ParseException e) {
163 System.out.println(e.getMessage());
164 printHelp(formatter);
168 printHelp(formatter);
172 initLog(getOptionOrDefault(cmd, OPTION_SILENT_SHORT, false), null,
173 getOptionOrDefault(cmd, OPTION_DEBUG_SHORT, false) ? Level.DEBUG : Level.INFO);
174 } catch (ParseException e2) {
178 if(getOptionOrDefault(cmd, OPTION_HELP_SHORT, false)) {
179 printHelp(formatter);
182 } catch (ParseException e2) {
185 final String command = cmd.getOptionValue(OPTION_COMMAND_SHORT);
187 printHelp(formatter);
194 } catch (Exception e1) {
201 } catch (Exception e1) {
205 case CMD_CLEAR_DB_COMPLETE:
207 cmd_clear_db_complete(cmd);
208 } catch (Exception e1) {
212 case CMD_CREATE_PLUGIN_INIT_FILE:
214 String of = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
216 throw new Exception("please add the parameter output-file");
218 MavenDatabasePluginInitFile.create(Release.CURRENT_RELEASE, of);
219 } catch (Exception e) {
226 } catch (Exception e1) {
233 } catch (Exception e) {
237 case CMD_LIST_VERSION:
242 printHelp(formatter);
248 private static void printHelp(HelpFormatter formatter) {
249 formatter.printHelp(APPLICATION_NAME, options);
250 System.out.println("\nCommands:");
251 for (String[] c : commands) {
252 System.out.println(String.format("%10s\t%s", c[0], c[1]));
256 private static void cmd_listversion() {
258 System.out.println("Database Releases:");
259 final String format = "%15s\t%8s";
260 System.out.println(String.format(format, "Name", "Version"));
261 for (Release r : Release.values()) {
263 System.out.println(String.format(format, r.getValue(),
264 r.getDBSuffix() != null && r.getDBSuffix().length() > 1 ? r.getDBSuffix().substring(1) : ""));
269 private static void cmd_dbimport(CommandLine cmd) throws Exception {
270 String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
271 String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
272 String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
273 String filename = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
274 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
275 if (filename == null) {
276 throw new Exception("please add output file parameter");
278 long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000;
279 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
280 username, password, trustAll, timeoutms);
281 DataMigrationReport report = service.importData(filename, false);
283 if(!report.completed()) {
284 throw new Exception("db import seems to be not executed completed");
288 private static void cmd_dbexport(CommandLine cmd) throws Exception {
289 String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
290 String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
291 String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
292 String filename = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
293 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
294 if (filename == null) {
295 throw new Exception("please add output file parameter");
297 long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000;
298 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
299 username, password, trustAll, timeoutms);
300 DataMigrationReport report = service.exportData(filename);
302 if(!report.completed()) {
303 throw new Exception("db export seems to be not executed completed");
308 private static int exit(Exception e) {
310 LOG.error("Error during execution: {}", e);
312 System.err.println(e);
317 private static void cmd_clear_db(CommandLine cmd) throws Exception {
318 Release r = getOptionOrDefault(cmd, OPTION_VERSION_SHORT, Release.CURRENT_RELEASE);
319 String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
320 String dbPrefix = getOptionOrDefault(cmd, OPTION_DATABASEPREFIX_SHORT, DEFAULT_DBPREFIX);
321 String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
322 String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
323 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
324 long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000;
325 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
326 username, password, trustAll, timeoutms);
327 if (!service.clearDatabase(r, dbPrefix,timeoutms)) {
328 throw new Exception("failed to init database");
331 private static void cmd_clear_db_complete(CommandLine cmd) throws Exception {
332 String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
333 String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
334 String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
335 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
336 long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000;
337 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
338 username, password, trustAll, timeoutms);
339 if (!service.clearCompleteDatabase(timeoutms)) {
340 throw new Exception("failed to init database");
344 private static void cmd_init_db(CommandLine cmd) throws Exception {
345 Release r = getOptionOrDefault(cmd, OPTION_VERSION_SHORT, Release.CURRENT_RELEASE);
346 int numShards = getOptionOrDefault(cmd, OPTION_SHARDS_SHORT, DEFAULT_SHARDS);
347 int numReplicas = getOptionOrDefault(cmd, OPTION_REPLICAS_SHORT, DEFAULT_REPLICAS);
348 String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
349 String dbPrefix = getOptionOrDefault(cmd, OPTION_DATABASEPREFIX_SHORT, DEFAULT_DBPREFIX);
350 String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
351 String password = getOptionOrDefault(cmd,OPTION_DATABASEPASSWORD_SHORT, null);
352 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
353 long timeoutms = getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, 30)*1000;
354 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
355 username, password, trustAll, timeoutms);
356 boolean forceRecreate = cmd.hasOption(OPTION_FORCE_RECREATE_SHORT);
357 if (!service.initDatabase(r, numShards, numReplicas, dbPrefix, forceRecreate,timeoutms)) {
358 throw new Exception("failed to init database");
363 private static Options init() {
364 Options result = new Options();
365 result.addOption(createOption(OPTION_COMMAND_SHORT, "cmd", true, "command to execute", false));
366 result.addOption(createOption(OPTION_DATABASE_SHORT, "dburl", true, "database url", false));
367 result.addOption(createOption(OPTION_DATABASEUSER_SHORT, "db-username", true, "database basic auth username", false));
368 result.addOption(createOption(OPTION_DATABASEPASSWORD_SHORT, "db-password", true, "database basic auth password", false));
369 result.addOption(createOption(OPTION_REPLICAS_SHORT, "replicas", true, "amount of replicas", false));
370 result.addOption(createOption(OPTION_SHARDS_SHORT, "shards", true, "amount of shards", false));
371 result.addOption(createOption(OPTION_DATABASEPREFIX_SHORT, "prefix", true, "prefix for db indices", false));
372 result.addOption(createOption(OPTION_VERSION_SHORT, "version", true, "version", false));
373 result.addOption(createOption(OPTION_DEBUG_SHORT, "verbose", false, "verbose mode", false));
374 result.addOption(createOption(OPTION_TRUSTINSECURESSL_SHORT, "trust-insecure", false,
375 "trust insecure ssl certs", false));
376 result.addOption(createOption(OPTION_DATABASEWAIT_SHORT, "wait", true, "wait for yellow status with timeout in seconds", false));
378 createOption(OPTION_FORCE_RECREATE_SHORT, "force-recreate", false, "delete if sth exists", false));
379 result.addOption(createOption(OPTION_SILENT_SHORT, OPTION_SILENT, false, "prevent console output", false));
380 result.addOption(createOption(OPTION_OUTPUTFILE_SHORT, "output-file", true, "file to write into", false));
381 result.addOption(createOption(OPTION_INPUTFILE_SHORT, "input-file", true, "file to read from", false));
382 result.addOption(createOption(OPTION_HELP_SHORT,"help",false,"show help",false));
394 private static Option createOption(String opt, String longOpt, boolean hasArg, String description,
396 Option o = new Option(opt, longOpt, hasArg, description);
397 o.setRequired(required);
400 // end of private methods