4b201bccc4ea9a5dd2f4f0a8b5e2dc01ae5ea719
[ccsdk/features.git] /
1 /*
2  * ============LICENSE_START=======================================================
3  * ONAP : ccsdk features
4  * ================================================================================
5  * Copyright (C) 2020 highstreet technologies GmbH Intellectual Property.
6  * All rights reserved.
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
11  *
12  *     http://www.apache.org/licenses/LICENSE-2.0
13  *
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=========================================================
20  *
21  */
22 package org.onap.ccsdk.features.sdnr.wt.dataprovider.setup;
23
24 import java.util.Arrays;
25 import java.util.List;
26
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;
39
40 /**
41  * @author Michael Dürre
42  *
43  */
44 public class Program {
45
46     // constants
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";
54
55     private static final String CMD_INITDB_DESCRIPTION = "initialize databse indices and aliases";
56     private static final String CMD_CLEAR_DB_DESCRIPTION = "delete database indices and aliases for current release";
57     private static final String CMD_CLEAR_DB_COMPLETE_DESCRIPTION = "delete all database indices and aliases";
58
59     private static final String CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION = "create maven plugin file";
60     private static final String CMD_IMPORT_DESCRIPTION = "import data into database";
61     private static final String CMD_EXPORT_DESCRIPTION = "export data from database";
62     private static final String CMD_LIST_VERSION_DESCRIPTION = "list release versions";
63
64     private static final List<String[]> commands = Arrays.asList(new String[] {CMD_INITDB, CMD_INITDB_DESCRIPTION},
65             new String[] {CMD_CLEAR_DB, CMD_CLEAR_DB_DESCRIPTION},
66             new String[] {CMD_CLEAR_DB_COMPLETE, CMD_CLEAR_DB_COMPLETE_DESCRIPTION},
67             new String[] {CMD_CREATE_PLUGIN_INIT_FILE, CMD_CREATE_PLUGIN_INIT_FILE_DESCRIPTION},
68             new String[] {CMD_IMPORT, CMD_IMPORT_DESCRIPTION}, new String[] {CMD_EXPORT, CMD_EXPORT_DESCRIPTION},
69             new String[] {CMD_LIST_VERSION, CMD_LIST_VERSION_DESCRIPTION});
70     private static final String APPLICATION_NAME = "SDNR DataMigrationTool";
71
72     private static final int DEFAULT_SHARDS = 5;
73     private static final int DEFAULT_REPLICAS = 1;
74     private static final int DEFAULT_DATABASEWAIT_SECONDS = 30;
75     private static final String DEFAULT_DBURL = "http://sdnrdb:9200";
76     private static final String DEFAULT_DBPREFIX = "";
77     private static final boolean DEFAULT_TRUSTINSECURESSL = false;
78
79     private static final String OPTION_FORCE_RECREATE_SHORT = "f";
80     private static final String OPTION_FORCE_RECREATE_LONG = "force-recreate";
81     private static final String OPTION_SILENT_SHORT = "n";
82     private static final String OPTION_SILENT = "silent";
83     private static final String OPTION_VERSION_SHORT = "v";
84     private static final String OPTION_VERSION_LONG = "version";
85     private static final String OPTION_SHARDS_SHORT = "s";
86     private static final String OPTION_SHARDS_LONG = "shards";
87     private static final String OPTION_REPLICAS_SHORT = "r";
88     private static final String OPTION_REPLICAS_LONG = "replicas";
89     private static final String OPTION_OUTPUTFILE_SHORT = "of";
90     private static final String OPTION_OUTPUTFILE_LONG = "output-file";
91     private static final String OPTION_INPUTFILE_SHORT = "if";
92     private static final String OPTION_INPUTFILE_LONG = "input-file";
93     private static final String OPTION_DEBUG_SHORT = "x";
94     private static final String OPTION_DEBUG_LONG = "verbose";
95     private static final String OPTION_TRUSTINSECURESSL_SHORT = "k";
96     private static final String OPTION_TRUSTINSECURESSL_LONG = "trust-insecure";
97     private static final String OPTION_DATABASE_SHORT = "db";
98     private static final String OPTION_DATABASE_LONG = "dburl";
99     private static final String OPTION_COMMAND_SHORT = "c";
100     private static final String OPTION_COMMAND_LONG = "cmd";
101     private static final String OPTION_DATABASEUSER_SHORT = "dbu";
102     private static final String OPTION_DATABASEUSER_LONG = "db-username";
103     private static final String OPTION_DATABASEPASSWORD_SHORT = "dbp";
104     private static final String OPTION_DATABASEPASSWORD_LONG = "db-password";
105     private static final String OPTION_DATABASEPREFIX_SHORT = "p";
106     private static final String OPTION_DATABASEPREFIX_LONG = "prefix";
107     private static final String OPTION_DATABASEWAIT_SHORT = "w";
108     private static final String OPTION_DATABASEWAIT_LONG = "wait";
109     private static final String OPTION_HELP_SHORT = "h";
110     private static final String OPTION_HELP_LONG = "help";
111     // end of constants
112
113     // variables
114     private static Options options = init();
115     private static Log LOG = null;
116     // end of variables
117
118     // public methods
119     public static void main(String[] args) {
120         System.exit(main2(args));
121     }
122     // end of public methods
123
124     // private methods
125     @SuppressWarnings("unchecked")
126     private static <T> T getOptionOrDefault(CommandLine cmd, String option, T def) throws ParseException {
127         if (def instanceof Boolean) {
128             return cmd.hasOption(option) ? (T) Boolean.TRUE : def;
129         }
130         if (def instanceof Integer) {
131             return cmd.hasOption(option) ? (T) Integer.valueOf(cmd.getOptionValue(option)) : def;
132         }
133         if (def instanceof Long) {
134             return cmd.hasOption(option) ? (T) Long.valueOf(cmd.getOptionValue(option)) : def;
135         }
136         if (def instanceof Release) {
137             return cmd.hasOption(option) ? (T) Release.getValueBySuffix(cmd.getOptionValue(option)) : def;
138         }
139         if (cmd.hasOption(option) && cmd.getOptionValue(option) != null) {
140             if (option.equals(OPTION_VERSION_SHORT)) {
141                 String v = cmd.getOptionValue(option);
142                 return (T) Release.getValueBySuffix(v.startsWith("-") ? v : "-" + v);
143             } else {
144                 return (T) cmd.getParsedOptionValue(option);
145             }
146         }
147         return def;
148     }
149
150     private static void initLog(boolean silent, String logfile, Level loglvl) {
151         Logger.getRootLogger().getLoggerRepository().resetConfiguration();
152         LOG = LogFactory.getLog(Program.class);
153         if (!silent) {
154             ConsoleAppender console = new ConsoleAppender(); // create appender
155             // configure the appender
156             String PATTERN = "%d [%p|%C{1}] %m%n";
157             console.setLayout(new PatternLayout(PATTERN));
158             console.setThreshold(loglvl);
159             console.activateOptions();
160             // add appender to any Logger (here is root)
161             Logger.getRootLogger().addAppender(console);
162         }
163         if (logfile != null) {
164             RollingFileAppender fa = new RollingFileAppender();
165             fa.setName("FileLogger");
166             fa.setFile(logfile);
167             fa.setLayout(new PatternLayout("%d %-5p [%c] %m%n"));
168             fa.setThreshold(loglvl);
169             fa.setMaximumFileSize(10000000);
170             fa.setAppend(true);
171             fa.setMaxBackupIndex(5);
172             fa.activateOptions();
173             // add appender to any Logger (here is root)
174             Logger.getRootLogger().addAppender(fa);
175         }
176         // repeat with all other desired appenders
177     }
178
179     private static int main2(String[] args) {
180
181         CommandLineParser parser = new DefaultParser();
182         HelpFormatter formatter = new HelpFormatter();
183         CommandLine cmd = null;
184
185         try {
186             cmd = parser.parse(options, args);
187         } catch (ParseException e) {
188             System.out.println(e.getMessage());
189             printHelp(formatter);
190             return 1;
191         }
192         if (cmd == null) {
193             printHelp(formatter);
194             return 1;
195         }
196         try {
197             initLog(getOptionOrDefault(cmd, OPTION_SILENT_SHORT, false), null,
198                     getOptionOrDefault(cmd, OPTION_DEBUG_SHORT, false) ? Level.DEBUG : Level.INFO);
199         } catch (ParseException e2) {
200
201         }
202         try {
203             if (getOptionOrDefault(cmd, OPTION_HELP_SHORT, false)) {
204                 printHelp(formatter);
205                 return 0;
206             }
207         } catch (ParseException e2) {
208             return exit(e2);
209         }
210         final String command = cmd.getOptionValue(OPTION_COMMAND_SHORT);
211         if (command == null) {
212             printHelp(formatter);
213             return 1;
214         }
215         switch (command) {
216             case CMD_INITDB:
217                 try {
218                     cmd_init_db(cmd);
219                 } catch (Exception e1) {
220                     return exit(e1);
221                 }
222                 break;
223             case CMD_CLEAR_DB:
224                 try {
225                     cmd_clear_db(cmd);
226                 } catch (Exception e1) {
227                     return exit(e1);
228                 }
229                 break;
230             case CMD_CLEAR_DB_COMPLETE:
231                 try {
232                     cmd_clear_db_complete(cmd);
233                 } catch (Exception e1) {
234                     return exit(e1);
235                 }
236                 break;
237             case CMD_CREATE_PLUGIN_INIT_FILE:
238                 try {
239                     String of = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
240                     if (of == null) {
241                         throw new Exception("please add the parameter output-file");
242                     }
243                     MavenDatabasePluginInitFile
244                             .create(getOptionOrDefault(cmd, OPTION_VERSION_SHORT, Release.CURRENT_RELEASE), of);
245                 } catch (Exception e) {
246                     return exit(e);
247                 }
248                 break;
249             case CMD_IMPORT:
250                 try {
251                     cmd_dbimport(cmd);
252                 } catch (Exception e1) {
253                     return exit(e1);
254                 }
255                 break;
256             case CMD_EXPORT:
257                 try {
258                     cmd_dbexport(cmd);
259                 } catch (Exception e) {
260                     return exit(e);
261                 }
262                 break;
263             case CMD_LIST_VERSION:
264                 cmd_listversion();
265                 break;
266
267             default:
268                 printHelp(formatter);
269                 return 1;
270         }
271         return 0;
272     }
273
274     private static void printHelp(HelpFormatter formatter) {
275         formatter.printHelp(APPLICATION_NAME, options);
276         System.out.println("\nCommands:");
277         for (String[] c : commands) {
278             System.out.println(String.format("%10s\t%s", c[0], c[1]));
279         }
280     }
281
282     private static void cmd_listversion() {
283
284         System.out.println("Database Releases:");
285         final String format = "%15s\t%8s";
286         System.out.println(String.format(format, "Name", "Version"));
287         for (Release r : Release.values()) {
288
289             System.out.println(String.format(format, r.getValue(),
290                     r.getDBSuffix() != null && r.getDBSuffix().length() > 1 ? r.getDBSuffix().substring(1) : ""));
291         }
292
293     }
294
295     private static void cmd_dbimport(CommandLine cmd) throws Exception {
296         String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
297         String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
298         String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
299         String filename = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
300         boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, DEFAULT_TRUSTINSECURESSL);
301         if (filename == null) {
302             throw new Exception("please add output file parameter");
303         }
304         long timeoutms = getTimeoutOptionMillis(cmd);
305         DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)},
306                 username, password, trustAll, timeoutms);
307         DataMigrationReport report = service.importData(filename, false);
308         LOG.info(report);
309         if (!report.completed()) {
310             throw new Exception("db import seems to be not executed completed");
311         }
312         LOG.info("database import completed successfully");
313     }
314
315     private static void cmd_dbexport(CommandLine cmd) throws Exception {
316         String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
317         String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
318         String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
319         String filename = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
320         boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, DEFAULT_TRUSTINSECURESSL);
321         if (filename == null) {
322             throw new Exception("please add output file parameter");
323         }
324         long timeoutms = getTimeoutOptionMillis(cmd);
325         DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)},
326                 username, password, trustAll, timeoutms);
327         DataMigrationReport report = service.exportData(filename);
328         LOG.info(report);
329         if (!report.completed()) {
330             throw new Exception("db export seems to be not executed completed");
331         }
332         LOG.info("database export completed successfully");
333     }
334
335     private static int exit(Exception e) {
336         if (LOG != null) {
337             LOG.error("Error during execution: {}", e);
338         } else {
339             System.err.println(e);
340         }
341         return 1;
342     }
343
344     private static void cmd_clear_db(CommandLine cmd) throws Exception {
345         Release r = getOptionOrDefault(cmd, OPTION_VERSION_SHORT, (Release) null);
346         String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
347         String dbPrefix = getOptionOrDefault(cmd, OPTION_DATABASEPREFIX_SHORT, DEFAULT_DBPREFIX);
348         String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
349         String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
350         boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, DEFAULT_TRUSTINSECURESSL);
351         long timeoutms = getTimeoutOptionMillis(cmd);
352         DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)},
353                 username, password, trustAll, timeoutms);
354         if (!service.clearDatabase(r, dbPrefix, timeoutms)) {
355             throw new Exception("failed to init database");
356         }
357         LOG.info("database clear completed successfully");
358     }
359
360     private static void cmd_clear_db_complete(CommandLine cmd) throws Exception {
361         String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
362         String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
363         String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
364         boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, DEFAULT_TRUSTINSECURESSL);
365         long timeoutms = getTimeoutOptionMillis(cmd);
366         DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)},
367                 username, password, trustAll, timeoutms);
368         if (!service.clearCompleteDatabase(timeoutms)) {
369             throw new Exception("failed to init database");
370         }
371         LOG.info("database complete clear completed successfully");
372     }
373
374     private static void cmd_init_db(CommandLine cmd) throws Exception {
375         Release r = getOptionOrDefault(cmd, OPTION_VERSION_SHORT, (Release) null);
376         int numShards = getOptionOrDefault(cmd, OPTION_SHARDS_SHORT, DEFAULT_SHARDS);
377         int numReplicas = getOptionOrDefault(cmd, OPTION_REPLICAS_SHORT, DEFAULT_REPLICAS);
378         String dbUrl = getOptionOrDefault(cmd, OPTION_DATABASE_SHORT, DEFAULT_DBURL);
379         String dbPrefix = getOptionOrDefault(cmd, OPTION_DATABASEPREFIX_SHORT, DEFAULT_DBPREFIX);
380         String username = getOptionOrDefault(cmd, OPTION_DATABASEUSER_SHORT, null);
381         String password = getOptionOrDefault(cmd, OPTION_DATABASEPASSWORD_SHORT, null);
382         boolean trustAll = getOptionOrDefault(cmd, OPTION_TRUSTINSECURESSL_SHORT, DEFAULT_TRUSTINSECURESSL);
383         long timeoutms = getTimeoutOptionMillis(cmd);
384         DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] {HostInfo.parse(dbUrl)},
385                 username, password, trustAll, timeoutms);
386         boolean forceRecreate = cmd.hasOption(OPTION_FORCE_RECREATE_SHORT);
387         if (!service.initDatabase(r, numShards, numReplicas, dbPrefix, forceRecreate, timeoutms)) {
388             throw new Exception("failed to init database");
389         }
390         LOG.info("database init completed successfully");
391
392     }
393
394     private static Options init() {
395         Options result = new Options();
396         result.addOption(createOption(OPTION_COMMAND_SHORT, OPTION_COMMAND_LONG, true, "command to execute", false));
397         result.addOption(createOption(OPTION_DATABASE_SHORT, OPTION_DATABASE_LONG, true, "database url", false));
398         result.addOption(createOption(OPTION_DATABASEUSER_SHORT, OPTION_DATABASEUSER_LONG, true,
399                 "database basic auth username", false));
400         result.addOption(createOption(OPTION_DATABASEPASSWORD_SHORT, OPTION_DATABASEPASSWORD_LONG, true,
401                 "database basic auth password", false));
402         result.addOption(createOption(OPTION_REPLICAS_SHORT, OPTION_REPLICAS_LONG, true, "amount of replicas", false));
403         result.addOption(createOption(OPTION_SHARDS_SHORT, OPTION_SHARDS_LONG, true, "amount of shards", false));
404         result.addOption(createOption(OPTION_DATABASEPREFIX_SHORT, OPTION_DATABASEPREFIX_LONG, true,
405                 "prefix for db indices", false));
406         result.addOption(createOption(OPTION_VERSION_SHORT, OPTION_VERSION_LONG, true, "version", false));
407         result.addOption(createOption(OPTION_DEBUG_SHORT, OPTION_DEBUG_LONG, false, "verbose mode", false));
408         result.addOption(createOption(OPTION_TRUSTINSECURESSL_SHORT, OPTION_TRUSTINSECURESSL_LONG, false,
409                 "trust insecure ssl certs", false));
410         result.addOption(createOption(OPTION_DATABASEWAIT_SHORT, OPTION_DATABASEWAIT_LONG, true,
411                 "wait for yellow status with timeout in seconds", false));
412         result.addOption(createOption(OPTION_FORCE_RECREATE_SHORT, OPTION_FORCE_RECREATE_LONG, false,
413                 "delete if sth exists", false));
414         result.addOption(createOption(OPTION_SILENT_SHORT, OPTION_SILENT, false, "prevent console output", false));
415         result.addOption(
416                 createOption(OPTION_OUTPUTFILE_SHORT, OPTION_OUTPUTFILE_LONG, true, "file to write into", false));
417         result.addOption(createOption(OPTION_INPUTFILE_SHORT, OPTION_INPUTFILE_LONG, true, "file to read from", false));
418         result.addOption(createOption(OPTION_HELP_SHORT, OPTION_HELP_LONG, false, "show help", false));
419         return result;
420     }
421
422     private static long getTimeoutOptionMillis(CommandLine cmd) throws ParseException {
423         return getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, DEFAULT_DATABASEWAIT_SECONDS) * 1000;
424     }
425
426     /**
427      * create option for argparse lib
428      * 
429      * @param opt short option string
430      * @param longOpt long option string
431      * @param hasArg flag if has a parameter after option tag
432      * @param description description for help output
433      * @param required flag if is required for program
434      * @return option object for argparse lib
435      */
436     private static Option createOption(String opt, String longOpt, boolean hasArg, String description,
437             boolean required) {
438         Option o = new Option(opt, longOpt, hasArg, description);
439         o.setRequired(required);
440         return o;
441     }
442     // end of private methods
443 }