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;
26 import org.apache.commons.cli.CommandLine;
27 import org.apache.commons.cli.CommandLineParser;
28 import org.apache.commons.cli.DefaultParser;
29 import org.apache.commons.cli.HelpFormatter;
30 import org.apache.commons.cli.Option;
31 import org.apache.commons.cli.Options;
32 import org.apache.commons.cli.ParseException;
33 import org.apache.commons.logging.Log;
34 import org.apache.commons.logging.LogFactory;
35 import org.apache.log4j.ConsoleAppender;
36 import org.apache.log4j.Level;
37 import org.apache.log4j.Logger;
38 import org.apache.log4j.PatternLayout;
39 import org.apache.log4j.RollingFileAppender;
40 import org.onap.ccsdk.features.sdnr.wt.common.database.config.HostInfo;
41 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.DataMigrationReport;
42 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.MavenDatabasePluginInitFile;
43 import org.onap.ccsdk.features.sdnr.wt.dataprovider.setup.data.Release;
46 * @author Michael Dürre
49 public class Program {
52 private static final String CMD_INITDB = "init";
53 private static final String CMD_CLEAR_DB = "delete";
54 private static final String CMD_CLEAR_DB_COMPLETE = "clear";
55 private static final String CMD_CREATE_PLUGIN_INIT_FILE = "pluginfile";
56 private static final String CMD_IMPORT = "import";
57 private static final String CMD_EXPORT = "export";
58 private static final String CMD_LIST_VERSION = "list";
60 private static final String CMD_INITDB_DESCRIPTION = "initialize databse indices and aliases";
61 private static final String CMD_CLEAR_DB_DESCRIPTION = "delete database indices and aliases for current release";
62 private static final String CMD_CLEAR_DB_COMPLETE_DESCRIPTION = "delete all database indices and aliases";
64 private static final String CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION = "create maven plugin file";
65 private static final String CMD_IMPORT_DESCRIPTION = "import data into database";
66 private static final String CMD_EXPORT_DESCRIPTION = "export data from database";
67 private static final String CMD_LIST_VERSION_DESCRIPTION = "list release versions";
69 private static final List<String[]> commands = Arrays.asList(new String[] {CMD_INITDB, CMD_INITDB_DESCRIPTION},
70 new String[] {CMD_CLEAR_DB, CMD_CLEAR_DB_DESCRIPTION},
71 new String[] {CMD_CLEAR_DB_COMPLETE, CMD_CLEAR_DB_COMPLETE_DESCRIPTION},
72 new String[] {CMD_CREATE_PLUGIN_INIT_FILE, CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION},
73 new String[] {CMD_IMPORT, CMD_IMPORT_DESCRIPTION}, new String[] {CMD_EXPORT, CMD_EXPORT_DESCRIPTION},
74 new String[] {CMD_LIST_VERSION, CMD_LIST_VERSION_DESCRIPTION});
75 private static final String APPLICATION_NAME = "SDNR DataMigrationTool";
77 private static final int DEFAULT_SHARDS = 5;
78 private static final int DEFAULT_REPLICAS = 1;
79 private static final int DEFAULT_DATABASEWAIT_SECONDS = 30;
80 private static final String DEFAULT_DBURL = "http://sdnrdb:9200";
81 private static final String DEFAULT_DBPREFIX = "";
82 private static final boolean DEFAULT_TRUSTINSECURESSL = false;
84 private static final String OPTION_FORCE_RECREATE_SHORT = "f";
85 private static final String OPTION_FORCE_RECREATE_LONG = "force-recreate";
86 private static final String OPTION_SILENT_SHORT = "n";
87 private static final String OPTION_SILENT = "silent";
88 private static final String OPTION_VERSION_SHORT = "v";
89 private static final String OPTION_VERSION_LONG = "version";
90 private static final String OPTION_SHARDS_SHORT = "s";
91 private static final String OPTION_SHARDS_LONG = "shards";
92 private static final String OPTION_REPLICAS_SHORT = "r";
93 private static final String OPTION_REPLICAS_LONG = "replicas";
94 private static final String OPTION_OUTPUTFILE_SHORT = "of";
95 private static final String OPTION_OUTPUTFILE_LONG = "output-file";
96 private static final String OPTION_INPUTFILE_SHORT = "if";
97 private static final String OPTION_INPUTFILE_LONG = "input-file";
98 private static final String OPTION_DEBUG_SHORT = "x";
99 private static final String OPTION_DEBUG_LONG = "verbose";
100 private static final String OPTION_TRUSTINSECURESSL_SHORT = "k";
101 private static final String OPTION_TRUSTINSECURESSL_LONG = "trust-insecure";
102 private static final String OPTION_DATABASE_SHORT = "db";
103 private static final String OPTION_DATABASE_LONG = "dburl";
104 private static final String OPTION_COMMAND_SHORT = "c";
105 private static final String OPTION_COMMAND_LONG = "cmd";
106 private static final String OPTION_DATABASEUSER_SHORT = "dbu";
107 private static final String OPTION_DATABASEUSER_LONG = "db-username";
108 private static final String OPTION_DATABASEPASSWORD_SHORT = "dbp";
109 private static final String OPTION_DATABASEPASSWORD_LONG = "db-password";
110 private static final String OPTION_DATABASEPREFIX_SHORT = "p";
111 private static final String OPTION_DATABASEPREFIX_LONG = "prefix";
112 private static final String OPTION_DATABASEWAIT_SHORT = "w";
113 private static final String OPTION_DATABASEWAIT_LONG = "wait";
114 private static final String OPTION_HELP_SHORT = "h";
115 private static final String OPTION_HELP_LONG = "help";
119 private static Options options = init();
120 private static Log LOG = null;
124 public static void main(String[] args) {
125 System.exit(main2(args));
127 // end of public methods
130 @SuppressWarnings("unchecked")
131 private static <T> T getOptionOrDefault(CommandLine cmd, String option, T def) throws ParseException {
132 if (def instanceof Boolean) {
133 return cmd.hasOption(option) ? (T) Boolean.TRUE : def;
135 if (def instanceof Integer) {
136 return cmd.hasOption(option) ? (T) Integer.valueOf(cmd.getOptionValue(option)) : def;
138 if (def instanceof Long) {
139 return cmd.hasOption(option) ? (T) Long.valueOf(cmd.getOptionValue(option)) : def;
141 if (def instanceof Release) {
142 return cmd.hasOption(option) ? (T) Release.getValueBySuffix(cmd.getOptionValue(option)) : def;
144 if (cmd.hasOption(option) && cmd.getOptionValue(option) != null) {
145 if (option.equals(OPTION_VERSION_SHORT)) {
146 String v = cmd.getOptionValue(option);
147 return (T) Release.getValueBySuffix(v.startsWith("-") ? v : "-" + v);
149 return (T) cmd.getParsedOptionValue(option);
155 private static void initLog(boolean silent, String logfile, Level loglvl) {
156 Logger.getRootLogger().getLoggerRepository().resetConfiguration();
157 LOG = LogFactory.getLog(Program.class);
159 ConsoleAppender console = new ConsoleAppender(); // create appender
160 // configure the appender
161 String PATTERN = "%d [%p|%C{1}] %m%n";
162 console.setLayout(new PatternLayout(PATTERN));
163 console.setThreshold(loglvl);
164 console.activateOptions();
165 // add appender to any Logger (here is root)
166 Logger.getRootLogger().addAppender(console);
168 if (logfile != null) {
169 RollingFileAppender fa = new RollingFileAppender();
170 fa.setName("FileLogger");
172 fa.setLayout(new PatternLayout("%d %-5p [%c] %m%n"));
173 fa.setThreshold(loglvl);
174 fa.setMaximumFileSize(10000000);
176 fa.setMaxBackupIndex(5);
177 fa.activateOptions();
178 // add appender to any Logger (here is root)
179 Logger.getRootLogger().addAppender(fa);
181 // repeat with all other desired appenders
184 private static int main2(String[] args) {
186 CommandLineParser parser = new DefaultParser();
187 HelpFormatter formatter = new HelpFormatter();
188 CommandLine cmd = null;
191 cmd = parser.parse(options, args);
192 } catch (ParseException e) {
193 System.out.println(e.getMessage());
194 printHelp(formatter);
198 printHelp(formatter);
202 initLog(getOptionOrDefault(cmd, OPTION_SILENT_SHORT, false), null,
203 getOptionOrDefault(cmd, OPTION_DEBUG_SHORT, false) ? Level.DEBUG : Level.INFO);
204 } catch (ParseException e2) {
208 if (getOptionOrDefault(cmd, OPTION_HELP_SHORT, false)) {
209 printHelp(formatter);
212 } catch (ParseException e2) {
215 final String command = cmd.getOptionValue(OPTION_COMMAND_SHORT);
216 if (command == null) {
217 printHelp(formatter);
224 } catch (Exception e1) {
231 } catch (Exception e1) {
235 case CMD_CLEAR_DB_COMPLETE:
237 cmd_clear_db_complete(cmd);
238 } catch (Exception e1) {
242 case CMD_CREATE_PLUGIN_INIT_FILE:
244 String of = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
246 throw new Exception("please add the parameter output-file");
248 MavenDatabasePluginInitFile
249 .create(getOptionOrDefault(cmd, OPTION_VERSION_SHORT, Release.CURRENT_RELEASE), of);
250 } catch (Exception e) {
257 } catch (Exception e1) {
264 } catch (Exception e) {
268 case CMD_LIST_VERSION:
273 printHelp(formatter);
279 private static void printHelp(HelpFormatter formatter) {
280 formatter.printHelp(APPLICATION_NAME, options);
281 System.out.println("\nCommands:");
282 for (String[] c : commands) {
283 System.out.println(String.format("%10s\t%s", c[0], c[1]));
287 private static void cmd_listversion() {
289 System.out.println("Database Releases:");
290 final String format = "%15s\t%8s";
291 System.out.println(String.format(format, "Name", "Version"));
292 for (Release r : Release.values()) {
294 System.out.println(String.format(format, r.getValue(),
295 r.getDBSuffix() != null && r.getDBSuffix().length() > 1 ? r.getDBSuffix().substring(1) : ""));
300 private static void cmd_dbimport(CommandLine cmd) throws Exception {
301 DatabaseOptions options = new DatabaseOptions(cmd);
302 String filename = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
303 if (filename == null) {
304 throw new Exception("please add output file parameter");
306 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(options.getUrl())},
307 options.getUsername(), options.getPassword(), options.doTrustAll(), options.getTimeoutMs());
308 DataMigrationReport report = service.importData(filename, false);
310 if (!report.completed()) {
311 throw new Exception("db import seems to be not executed completed");
313 LOG.info("database import completed successfully");
316 private static void cmd_dbexport(CommandLine cmd) throws Exception {
317 DatabaseOptions options = new DatabaseOptions(cmd);
318 String filename = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
319 if (filename == null) {
320 throw new Exception("please add output file parameter");
322 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(options.getUrl())},
323 options.getUsername(), options.getPassword(), options.doTrustAll(), options.getTimeoutMs());
324 DataMigrationReport report = service.exportData(filename);
326 if (!report.completed()) {
327 throw new Exception("db export seems to be not executed completed");
329 LOG.info("database export completed successfully");
332 private static int exit(Exception e) {
334 LOG.error("Error during execution: {}", e);
336 System.err.println(e);
341 private static void cmd_clear_db(CommandLine cmd) throws Exception {
342 Release r = getOptionOrDefault(cmd, OPTION_VERSION_SHORT, (Release) null);
343 DatabaseOptions options = new DatabaseOptions(cmd);
344 String dbPrefix = getOptionOrDefault(cmd, OPTION_DATABASEPREFIX_SHORT, DEFAULT_DBPREFIX);
345 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(options.getUrl())},
346 options.getUsername(), options.getPassword(), options.doTrustAll(), options.getTimeoutMs());
347 if (!service.clearDatabase(r, dbPrefix, options.getTimeoutMs())) {
348 throw new Exception("failed to init database");
350 LOG.info("database clear completed successfully");
353 private static void cmd_clear_db_complete(CommandLine cmd) throws Exception {
354 DatabaseOptions options = new DatabaseOptions(cmd);
355 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(options.getUrl())},
356 options.getUsername(), options.getPassword(), options.doTrustAll(), options.getTimeoutMs());
357 if (!service.clearCompleteDatabase(options.getTimeoutMs())) {
358 throw new Exception("failed to init database");
360 LOG.info("database complete clear completed successfully");
363 private static void cmd_init_db(CommandLine cmd) throws Exception {
364 Release r = getOptionOrDefault(cmd, OPTION_VERSION_SHORT, (Release) null);
365 int numShards = getOptionOrDefault(cmd, OPTION_SHARDS_SHORT, DEFAULT_SHARDS);
366 int numReplicas = getOptionOrDefault(cmd, OPTION_REPLICAS_SHORT, DEFAULT_REPLICAS);
367 DatabaseOptions options = new DatabaseOptions(cmd);
368 String dbPrefix = getOptionOrDefault(cmd, OPTION_DATABASEPREFIX_SHORT, DEFAULT_DBPREFIX);
369 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(options.getUrl())},
370 options.getUsername(), options.getPassword(), options.doTrustAll(), options.getTimeoutMs());
371 boolean forceRecreate = cmd.hasOption(OPTION_FORCE_RECREATE_SHORT);
372 if (!service.initDatabase(r, numShards, numReplicas, dbPrefix, forceRecreate, options.getTimeoutMs())) {
373 throw new Exception("failed to init database");
375 LOG.info("database init completed successfully");
379 private static Options init() {
380 Options result = new Options();
381 result.addOption(createOption(OPTION_COMMAND_SHORT, OPTION_COMMAND_LONG, true, "command to execute", false));
382 result.addOption(createOption(OPTION_DATABASE_SHORT, OPTION_DATABASE_LONG, true, "database url", false));
383 result.addOption(createOption(OPTION_DATABASEUSER_SHORT, OPTION_DATABASEUSER_LONG, true,
384 "database basic auth username", false));
385 result.addOption(createOption(OPTION_DATABASEPASSWORD_SHORT, OPTION_DATABASEPASSWORD_LONG, true,
386 "database basic auth password", false));
387 result.addOption(createOption(OPTION_REPLICAS_SHORT, OPTION_REPLICAS_LONG, true, "amount of replicas", false));
388 result.addOption(createOption(OPTION_SHARDS_SHORT, OPTION_SHARDS_LONG, true, "amount of shards", false));
389 result.addOption(createOption(OPTION_DATABASEPREFIX_SHORT, OPTION_DATABASEPREFIX_LONG, true,
390 "prefix for db indices", false));
391 result.addOption(createOption(OPTION_VERSION_SHORT, OPTION_VERSION_LONG, true, "version", false));
392 result.addOption(createOption(OPTION_DEBUG_SHORT, OPTION_DEBUG_LONG, false, "verbose mode", false));
393 result.addOption(createOption(OPTION_TRUSTINSECURESSL_SHORT, OPTION_TRUSTINSECURESSL_LONG, false,
394 "trust insecure ssl certs", false));
395 result.addOption(createOption(OPTION_DATABASEWAIT_SHORT, OPTION_DATABASEWAIT_LONG, true,
396 "wait for yellow status with timeout in seconds", false));
397 result.addOption(createOption(OPTION_FORCE_RECREATE_SHORT, OPTION_FORCE_RECREATE_LONG, false,
398 "delete if sth exists", false));
399 result.addOption(createOption(OPTION_SILENT_SHORT, OPTION_SILENT, false, "prevent console output", false));
401 createOption(OPTION_OUTPUTFILE_SHORT, OPTION_OUTPUTFILE_LONG, true, "file to write into", false));
402 result.addOption(createOption(OPTION_INPUTFILE_SHORT, OPTION_INPUTFILE_LONG, true, "file to read from", false));
403 result.addOption(createOption(OPTION_HELP_SHORT, OPTION_HELP_LONG, false, "show help", false));
407 private static long getTimeoutOptionMillis(CommandLine cmd) throws ParseException {
408 return getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, DEFAULT_DATABASEWAIT_SECONDS) * 1000;
412 * create option for argparse lib
414 * @param opt short option string
415 * @param longOpt long option string
416 * @param hasArg flag if has a parameter after option tag
417 * @param description description for help output
418 * @param required flag if is required for program
419 * @return option object for argparse lib
421 private static Option createOption(String opt, String longOpt, boolean hasArg, String description,
423 Option o = new Option(opt, longOpt, hasArg, description);
424 o.setRequired(required);
427 // end of private methods
429 private static class DatabaseOptions{
430 private final String url;
431 private final String username;
432 private final String password;
433 private final boolean trustAll;
434 private final long timeoutMs;
436 public String getUrl() {
439 public String getUsername() {
440 return this.username;
442 public String getPassword() {
443 return this.password;
445 public boolean doTrustAll() {
446 return this.trustAll;
448 public long getTimeoutMs() {
449 return this.timeoutMs;
451 public DatabaseOptions(CommandLine cmd) throws ParseException {
452 this.url = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
453 this.username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
454 this.password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
455 this.trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, DEFAULT_TRUSTINSECURESSL);
456 this.timeoutMs = getTimeoutOptionMillis(cmd);