d06ffe1ee3d672f01577c4a30024f7d86f5b22bd
[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 = "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";
61
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";
89     // end of constants
90         
91         // variables
92     private static Options options = init();
93     private static Log LOG = null;
94     // end of variables
95     
96     // public methods
97     public static void main(String[] args) {
98         System.exit( main2(args) );
99     }
100     // end of public methods
101     
102     // private 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;
107         }
108         if (def instanceof Integer) {
109             return cmd.hasOption(option) ? (T) Integer.valueOf(cmd.getOptionValue(option)) : def;
110         }
111         if (def instanceof Long) {
112             return cmd.hasOption(option) ? (T) Long.valueOf(cmd.getOptionValue(option)) : def;
113         }
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);
118             } else {
119                 return (T) cmd.getParsedOptionValue(option);
120             }
121         }
122         return def;
123     }
124
125     private static void initLog(boolean silent, String logfile, Level loglvl) {
126         Logger.getRootLogger().getLoggerRepository().resetConfiguration();
127         LOG = LogFactory.getLog(Program.class);
128         if (!silent) {
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);
137         }
138         if (logfile != null) {
139             RollingFileAppender fa = new RollingFileAppender();
140             fa.setName("FileLogger");
141             fa.setFile(logfile);
142             fa.setLayout(new PatternLayout("%d %-5p [%c] %m%n"));
143             fa.setThreshold(loglvl);
144             fa.setMaximumFileSize(10000000);
145             fa.setAppend(true);
146             fa.setMaxBackupIndex(5);
147             fa.activateOptions();
148             // add appender to any Logger (here is root)
149             Logger.getRootLogger().addAppender(fa);
150         }
151         // repeat with all other desired appenders
152     }
153
154     private static int main2(String[] args) {
155
156         CommandLineParser parser = new DefaultParser();
157         HelpFormatter formatter = new HelpFormatter();
158         CommandLine cmd = null;
159        
160         try {
161             cmd = parser.parse(options, args);
162         } catch (ParseException e) {
163             System.out.println(e.getMessage());
164             printHelp(formatter);
165             return 1;
166         }
167         if (cmd == null) {
168             printHelp(formatter);
169             return 1;
170         }
171         try {
172             initLog(getOptionOrDefault(cmd, OPTION_SILENT_SHORT, false), null,
173                     getOptionOrDefault(cmd, OPTION_DEBUG_SHORT, false) ? Level.DEBUG : Level.INFO);
174         } catch (ParseException e2) {
175
176         }
177         try {
178                         if(getOptionOrDefault(cmd, OPTION_HELP_SHORT, false)) {
179                             printHelp(formatter);
180                             return 0;
181                         }
182                 } catch (ParseException e2) {
183                         return exit(e2);
184                 }
185         final String command = cmd.getOptionValue(OPTION_COMMAND_SHORT);
186         if(command==null) {
187                 printHelp(formatter);
188             return 1;
189         }
190         switch (command) {
191         case CMD_INITDB:
192             try {
193                 cmd_init_db(cmd);
194             } catch (Exception e1) {
195                 return exit(e1);
196             }
197             break;
198         case CMD_CLEAR_DB:
199             try {
200                 cmd_clear_db(cmd);
201             } catch (Exception e1) {
202                 return exit(e1);
203             }
204             break;
205         case CMD_CLEAR_DB_COMPLETE:
206                 try {
207                 cmd_clear_db_complete(cmd);
208             } catch (Exception e1) {
209                 return exit(e1);
210             }
211             break;
212         case CMD_CREATE_PLUGIN_INIT_FILE:
213             try {
214                 String of = getOptionOrDefault(cmd, OPTION_OUTPUTFILE_SHORT, null);
215                 if (of == null) {
216                     throw new Exception("please add the parameter output-file");
217                 }
218                 MavenDatabasePluginInitFile.create(Release.CURRENT_RELEASE, of);
219             } catch (Exception e) {
220                 return exit(e);
221             }
222             break;
223         case CMD_IMPORT:
224             try {
225                 cmd_dbimport(cmd);
226             } catch (Exception e1) {
227                 return exit(e1);
228             }
229             break;
230         case CMD_EXPORT:
231             try {
232                 cmd_dbexport(cmd);
233             } catch (Exception e) {
234                 return exit(e);
235             }
236             break;
237         case CMD_LIST_VERSION:
238             cmd_listversion();
239             break;
240
241         default:
242             printHelp(formatter);
243             return 1;
244         }
245         return 0;
246     }
247
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]));
253         }
254     }
255
256     private static void cmd_listversion() {
257
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()) {
262
263             System.out.println(String.format(format, r.getValue(),
264                     r.getDBSuffix() != null && r.getDBSuffix().length() > 1 ? r.getDBSuffix().substring(1) : ""));
265         }
266
267     }
268
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");
277         }
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);
282         LOG.info(report);
283         if(!report.completed()) {
284             throw new Exception("db import seems to be not executed completed");
285         }
286     }
287
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");
296         }
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);
301         LOG.info(report);
302         if(!report.completed()) {
303             throw new Exception("db export seems to be not executed completed");
304         }
305
306     }
307
308     private static int exit(Exception e) {
309         if (LOG != null) {
310             LOG.error("Error during execution: {}", e);
311         } else {
312             System.err.println(e);
313         }
314         return 1;
315     }
316
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");
329         }
330     }
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");
341         }
342     }
343
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");
359         }
360
361     }
362
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));
377         result.addOption(
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));
383         return result;
384     }
385
386     /**
387      * @param opt
388      * @param longOpt
389      * @param hasArg
390      * @param description
391      * @param required
392      * @return
393      */
394     private static Option createOption(String opt, String longOpt, boolean hasArg, String description,
395             boolean required) {
396         Option o = new Option(opt, longOpt, hasArg, description);
397         o.setRequired(required);
398         return o;
399     }
400     // end of private methods
401 }