54204f17089ee3babaad3244cf586147720806d7
[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 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;
44
45 /**
46  * @author Michael Dürre
47  *
48  */
49 public class Program {
50
51     // constants
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";
59
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";
63
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";
68
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";
76
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;
83
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";
116     // end of constants
117
118     // variables
119     private static Options options = init();
120     private static Log LOG = null;
121     // end of variables
122
123     // public methods
124     public static void main(String[] args) {
125         System.exit(main2(args));
126     }
127     // end of public methods
128
129     // private 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;
134         }
135         if (def instanceof Integer) {
136             return cmd.hasOption(option) ? (T) Integer.valueOf(cmd.getOptionValue(option)) : def;
137         }
138         if (def instanceof Long) {
139             return cmd.hasOption(option) ? (T) Long.valueOf(cmd.getOptionValue(option)) : def;
140         }
141         if (def instanceof Release) {
142             return cmd.hasOption(option) ? (T) Release.getValueBySuffix(cmd.getOptionValue(option)) : def;
143         }
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);
148             } else {
149                 return (T) cmd.getParsedOptionValue(option);
150             }
151         }
152         return def;
153     }
154
155     private static void initLog(boolean silent, String logfile, Level loglvl) {
156         Logger.getRootLogger().getLoggerRepository().resetConfiguration();
157         LOG = LogFactory.getLog(Program.class);
158         if (!silent) {
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);
167         }
168         if (logfile != null) {
169             RollingFileAppender fa = new RollingFileAppender();
170             fa.setName("FileLogger");
171             fa.setFile(logfile);
172             fa.setLayout(new PatternLayout("%d %-5p [%c] %m%n"));
173             fa.setThreshold(loglvl);
174             fa.setMaximumFileSize(10000000);
175             fa.setAppend(true);
176             fa.setMaxBackupIndex(5);
177             fa.activateOptions();
178             // add appender to any Logger (here is root)
179             Logger.getRootLogger().addAppender(fa);
180         }
181         // repeat with all other desired appenders
182     }
183
184     private static int main2(String[] args) {
185
186         CommandLineParser parser = new DefaultParser();
187         HelpFormatter formatter = new HelpFormatter();
188         CommandLine cmd = null;
189
190         try {
191             cmd = parser.parse(options, args);
192         } catch (ParseException e) {
193             System.out.println(e.getMessage());
194             printHelp(formatter);
195             return 1;
196         }
197         if (cmd == null) {
198             printHelp(formatter);
199             return 1;
200         }
201         try {
202             initLog(getOptionOrDefault(cmd, OPTION_SILENT_SHORT, false), null,
203                     getOptionOrDefault(cmd, OPTION_DEBUG_SHORT, false) ? Level.DEBUG : Level.INFO);
204         } catch (ParseException e2) {
205
206         }
207         try {
208             if (getOptionOrDefault(cmd, OPTION_HELP_SHORT, false)) {
209                 printHelp(formatter);
210                 return 0;
211             }
212         } catch (ParseException e2) {
213             return exit(e2);
214         }
215         final String command = cmd.getOptionValue(OPTION_COMMAND_SHORT);
216         if (command == null) {
217             printHelp(formatter);
218             return 1;
219         }
220         switch (command) {
221             case CMD_INITDB:
222                 try {
223                     cmd_init_db(cmd);
224                 } catch (Exception e1) {
225                     return exit(e1);
226                 }
227                 break;
228             case CMD_CLEAR_DB:
229                 try {
230                     cmd_clear_db(cmd);
231                 } catch (Exception e1) {
232                     return exit(e1);
233                 }
234                 break;
235             case CMD_CLEAR_DB_COMPLETE:
236                 try {
237                     cmd_clear_db_complete(cmd);
238                 } catch (Exception e1) {
239                     return exit(e1);
240                 }
241                 break;
242             case CMD_CREATE_PLUGIN_INIT_FILE:
243                 try {
244                     String of = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
245                     if (of == null) {
246                         throw new Exception("please add the parameter output-file");
247                     }
248                     MavenDatabasePluginInitFile
249                             .create(getOptionOrDefault(cmd, OPTION_VERSION_SHORT, Release.CURRENT_RELEASE), of);
250                 } catch (Exception e) {
251                     return exit(e);
252                 }
253                 break;
254             case CMD_IMPORT:
255                 try {
256                     cmd_dbimport(cmd);
257                 } catch (Exception e1) {
258                     return exit(e1);
259                 }
260                 break;
261             case CMD_EXPORT:
262                 try {
263                     cmd_dbexport(cmd);
264                 } catch (Exception e) {
265                     return exit(e);
266                 }
267                 break;
268             case CMD_LIST_VERSION:
269                 cmd_listversion();
270                 break;
271
272             default:
273                 printHelp(formatter);
274                 return 1;
275         }
276         return 0;
277     }
278
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]));
284         }
285     }
286
287     private static void cmd_listversion() {
288
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()) {
293
294             System.out.println(String.format(format, r.getValue(),
295                     r.getDBSuffix() != null && r.getDBSuffix().length() > 1 ? r.getDBSuffix().substring(1) : ""));
296         }
297
298     }
299
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");
305         }
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);
309         LOG.info(report);
310         if (!report.completed()) {
311             throw new Exception("db import seems to be not executed completed");
312         }
313         LOG.info("database import completed successfully");
314     }
315
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");
321         }
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);
325         LOG.info(report);
326         if (!report.completed()) {
327             throw new Exception("db export seems to be not executed completed");
328         }
329         LOG.info("database export completed successfully");
330     }
331
332     private static int exit(Exception e) {
333         if (LOG != null) {
334             LOG.error("Error during execution: {}", e);
335         } else {
336             System.err.println(e);
337         }
338         return 1;
339     }
340
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");
349         }
350         LOG.info("database clear completed successfully");
351     }
352
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");
359         }
360         LOG.info("database complete clear completed successfully");
361     }
362
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");
374         }
375         LOG.info("database init completed successfully");
376
377     }
378
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));
400         result.addOption(
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));
404         return result;
405     }
406
407     private static long getTimeoutOptionMillis(CommandLine cmd) throws ParseException {
408         return getOptionOrDefault(cmd, OPTION_DATABASEWAIT_SHORT, DEFAULT_DATABASEWAIT_SECONDS) * 1000;
409     }
410
411     /**
412      * create option for argparse lib
413      *
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
420      */
421     private static Option createOption(String opt, String longOpt, boolean hasArg, String description,
422             boolean required) {
423         Option o = new Option(opt, longOpt, hasArg, description);
424         o.setRequired(required);
425         return o;
426     }
427     // end of private methods
428
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;
435
436         public String getUrl() {
437             return this.url;
438         }
439         public String getUsername() {
440             return this.username;
441         }
442         public String getPassword() {
443             return this.password;
444         }
445         public boolean doTrustAll() {
446             return this.trustAll;
447         }
448         public long getTimeoutMs() {
449             return this.timeoutMs;
450         }
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);
457         }
458     }
459 }