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 {
46 private static final String CMD_INITDB = "init";
47 private static final String CMD_CLEAR_DB = "delete";
48 private static final String CMD_CREATE_PLUGIN_INIT_FILE = "pluginfile";
49 private static final String CMD_IMPORT = "import";
50 private static final String CMD_EXPORT = "export";
51 private static final String CMD_LIST_VERSION = "list";
52 private static final String CMD_INITDB_DESCRIPTION = "initialize databse indices and aliases";
53 private static final String CMD_CLEAR_DB_DESCRIPTION = "clear database indices and aliases";
54 private static final String CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION = "create maven plugin file";
55 private static final String CMD_IMPORT_DESCRIPTION = "import data into database";
56 private static final String CMD_EXPORT_DESCRIPTION = "export data from database";
57 private static final String CMD_LIST_VERSION_DESCRIPTION = "list release versions";
59 private static final List<String[]> commands = Arrays.asList(new String[] { CMD_INITDB, CMD_INITDB_DESCRIPTION },
60 new String[] { CMD_CLEAR_DB, CMD_CLEAR_DB_DESCRIPTION },
61 new String[] { CMD_CREATE_PLUGIN_INIT_FILE, CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION },
62 new String[] { CMD_IMPORT, CMD_IMPORT_DESCRIPTION }, new String[] { CMD_EXPORT, CMD_EXPORT_DESCRIPTION },
63 new String[] { CMD_LIST_VERSION, CMD_LIST_VERSION_DESCRIPTION });
64 private static final String APPLICATION_NAME = "SDNR DataMigrationTool";
65 private static final int DEFAULT_SHARDS = 5;
66 private static final int DEFAULT_REPLICAS = 1;
67 private static final String DEFAULT_DBURL = "http://sdnrdb:9200";
68 private static final String DEFAULT_DBPREFIX = "";
69 private static final String OPTION_FORCE_RECREATE_SHORT = "f";
70 private static final String OPTION_SILENT_SHORT = "n";
71 private static final String OPTION_SILENT = "silent";
72 private static final String OPTION_VERSION_SHORT = "v";
73 private static final String OPTION_SHARDS_SHORT = "s";
74 private static final String OPTION_REPLICAS_SHORT = "r";
75 private static final String OPTION_OUTPUTFILE_SHORT = "of";
76 private static final String OPTION_INPUTFILE_SHORT = "if";
77 private static final String OPTION_DEBUG_SHORT = "x";
78 private static final String OPTION_TRUSTINSECURESSL_SHORT = "k";
79 private static final String OPTION_DATABSE_SHORT = "db";
81 private static Options options = init();
83 private static Log LOG = null;
85 @SuppressWarnings("unchecked")
86 private static <T> T getOptionOrDefault(CommandLine cmd, String option, T def) throws ParseException {
87 if (def instanceof Boolean) {
88 return cmd.hasOption(option) ? (T) Boolean.TRUE : def;
90 if (def instanceof Integer) {
91 return cmd.hasOption(option) ? (T) Integer.valueOf(cmd.getOptionValue(option)) : def;
93 if (def instanceof Long) {
94 return cmd.hasOption(option) ? (T) Long.valueOf(cmd.getOptionValue(option)) : def;
96 if (cmd.hasOption(option) && cmd.getOptionValue(option) != null) {
97 if (option.equals(OPTION_VERSION_SHORT)) {
98 String v = cmd.getOptionValue(option);
99 return (T) Release.getValueBySuffix(v.startsWith("-") ? v : "-" + v);
101 return (T) cmd.getParsedOptionValue(option);
107 private static void initLog(boolean silent, String logfile, Level loglvl) {
108 Logger.getRootLogger().getLoggerRepository().resetConfiguration();
109 LOG = LogFactory.getLog(Program.class);
111 ConsoleAppender console = new ConsoleAppender(); // create appender
112 // configure the appender
113 String PATTERN = "%d [%p|%C{1}] %m%n";
114 console.setLayout(new PatternLayout(PATTERN));
115 console.setThreshold(loglvl);
116 console.activateOptions();
117 // add appender to any Logger (here is root)
118 Logger.getRootLogger().addAppender(console);
120 if (logfile != null) {
121 RollingFileAppender fa = new RollingFileAppender();
122 fa.setName("FileLogger");
124 fa.setLayout(new PatternLayout("%d %-5p [%c] %m%n"));
125 fa.setThreshold(loglvl);
126 fa.setMaximumFileSize(10000000);
128 fa.setMaxBackupIndex(5);
129 fa.activateOptions();
130 // add appender to any Logger (here is root)
131 Logger.getRootLogger().addAppender(fa);
133 // repeat with all other desired appenders
136 public static void main(String[] args) {
137 CommandLineParser parser = new DefaultParser();
138 HelpFormatter formatter = new HelpFormatter();
139 CommandLine cmd = null;
141 cmd = parser.parse(options, args);
142 } catch (ParseException e) {
143 System.out.println(e.getMessage());
144 printHelp(formatter);
148 printHelp(formatter);
152 initLog(getOptionOrDefault(cmd, OPTION_SILENT_SHORT, false), null,
153 getOptionOrDefault(cmd, OPTION_DEBUG_SHORT, false) ? Level.DEBUG : Level.INFO);
154 } catch (ParseException e2) {
157 switch (cmd.getOptionValue("c")) {
161 } catch (Exception e1) {
168 } catch (Exception e1) {
172 case CMD_CREATE_PLUGIN_INIT_FILE:
174 String of = getOptionOrDefault(cmd, "of", null);
176 throw new Exception("please add the parameter output-file");
178 MavenDatabasePluginInitFile.create(Release.CURRENT_RELEASE, of);
179 } catch (Exception e) {
186 } catch (Exception e1) {
193 } catch (Exception e) {
197 case CMD_LIST_VERSION:
201 printHelp(formatter);
207 private static void printHelp(HelpFormatter formatter) {
208 formatter.printHelp(APPLICATION_NAME, options);
209 System.out.println("\nCommands:");
210 for (String[] c : commands) {
211 System.out.println(String.format("%10s\t%s", c[0], c[1]));
215 private static void cmd_listversion() {
217 System.out.println("Database Releases:");
218 final String format = "%15s\t%8s";
219 System.out.println(String.format(format, "Name", "Version"));
220 for (Release r : Release.values()) {
222 System.out.println(String.format(format, r.getValue(),
223 r.getDBSuffix() != null && r.getDBSuffix().length() > 1 ? r.getDBSuffix().substring(1) : ""));
228 private static void cmd_dbimport(CommandLine cmd) throws Exception {
229 String dbUrl = getOptionOrDefault(cmd, OPTION_DATABSE_SHORT, DEFAULT_DBURL);
230 String username = getOptionOrDefault(cmd, "dbu", null);
231 String password = getOptionOrDefault(cmd, "dbp", null);
232 String filename = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
233 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
234 if (filename == null) {
235 throw new Exception("please add output file parameter");
237 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
238 username, password, trustAll);
239 DataMigrationReport report = service.importData(filename, false);
241 if(!report.completed()) {
242 throw new Exception("db import seems to be not executed completed");
246 private static void cmd_dbexport(CommandLine cmd) throws Exception {
247 String dbUrl = getOptionOrDefault(cmd, "db", DEFAULT_DBURL);
248 String username = getOptionOrDefault(cmd, "dbu", null);
249 String password = getOptionOrDefault(cmd, "dbp", null);
250 String filename = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
251 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
252 if (filename == null) {
253 throw new Exception("please add output file parameter");
255 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
256 username, password, trustAll);
257 DataMigrationReport report = service.exportData(filename);
259 if(!report.completed()) {
260 throw new Exception("db export seems to be not executed completed");
265 private static void exit(Exception e) {
267 LOG.error("Error during execution: {}", e);
269 System.err.println(e);
274 private static void cmd_clear_db(CommandLine cmd) throws Exception {
275 Release r = getOptionOrDefault(cmd, OPTION_VERSION_SHORT, Release.CURRENT_RELEASE);
276 String dbUrl = getOptionOrDefault(cmd, OPTION_DATABSE_SHORT, DEFAULT_DBURL);
277 String dbPrefix = getOptionOrDefault(cmd, "p", DEFAULT_DBPREFIX);
278 String username = getOptionOrDefault(cmd, "dbu", null);
279 String password = getOptionOrDefault(cmd, "dbp", null);
280 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
281 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
282 username, password, trustAll);
283 long timeoutms = getOptionOrDefault(cmd, "w", 30)*1000;
284 if (!service.clearDatabase(r, dbPrefix,timeoutms)) {
285 throw new Exception("failed to init database");
289 private static void cmd_init_db(CommandLine cmd) throws Exception {
290 Release r = getOptionOrDefault(cmd, OPTION_VERSION_SHORT, Release.CURRENT_RELEASE);
291 int numShards = getOptionOrDefault(cmd, OPTION_SHARDS_SHORT, DEFAULT_SHARDS);
292 int numReplicas = getOptionOrDefault(cmd, OPTION_REPLICAS_SHORT, DEFAULT_REPLICAS);
293 String dbUrl = getOptionOrDefault(cmd, "db", DEFAULT_DBURL);
294 String dbPrefix = getOptionOrDefault(cmd, "p", DEFAULT_DBPREFIX);
295 String username = getOptionOrDefault(cmd, "dbu", null);
296 String password = getOptionOrDefault(cmd, "dbp", null);
297 boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, false);
298 DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
299 username, password, trustAll);
300 long timeoutms = getOptionOrDefault(cmd, "w", 30)*1000;
301 boolean forceRecreate = cmd.hasOption(OPTION_FORCE_RECREATE_SHORT);
302 if (!service.initDatabase(r, numShards, numReplicas, dbPrefix, forceRecreate,timeoutms)) {
303 throw new Exception("failed to init database");
308 private static Options init() {
309 Options result = new Options();
310 result.addOption(createOption("c", "cmd", true, "command to execute", true));
311 result.addOption(createOption(OPTION_DATABSE_SHORT, "dburl", true, "database url", false));
312 result.addOption(createOption("dbu", "db-username", true, "database basic auth username", false));
313 result.addOption(createOption("dbp", "db-password", true, "database basic auth password", false));
314 result.addOption(createOption(OPTION_REPLICAS_SHORT, "replicas", true, "amount of replicas", false));
315 result.addOption(createOption(OPTION_SHARDS_SHORT, "shards", true, "amount of shards", false));
316 result.addOption(createOption("p", "prefix", true, "prefix for db indices", false));
317 result.addOption(createOption(OPTION_VERSION_SHORT, "version", true, "version", false));
318 result.addOption(createOption(OPTION_DEBUG_SHORT, "verbose", false, "verbose mode", false));
319 result.addOption(createOption(OPTION_TRUSTINSECURESSL_SHORT, "trust-insecure", false,
320 "trust insecure ssl certs", false));
321 result.addOption(createOption("w", "wait", true, "wait for yellow status with timeout in seconds", false));
323 createOption(OPTION_FORCE_RECREATE_SHORT, "force-recreate", false, "delete if sth exists", false));
324 result.addOption(createOption(OPTION_SILENT_SHORT, OPTION_SILENT, false, "prevent console output", false));
325 result.addOption(createOption(OPTION_OUTPUTFILE_SHORT, "output-file", true, "file to write into", false));
326 result.addOption(createOption(OPTION_INPUTFILE_SHORT, "input-file", true, "file to read from", false));
339 private static Option createOption(String opt, String longOpt, boolean hasArg, String description,
341 Option o = new Option(opt, longOpt, hasArg, description);
342 o.setRequired(required);