a1b92e9b3cea7f0f9598f2fe9416f6282eeb7282
[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     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";
58
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";
80
81     private static Options options = init();
82
83     private static Log LOG = null;
84
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;
89         }
90         if (def instanceof Integer) {
91             return cmd.hasOption(option) ? (T) Integer.valueOf(cmd.getOptionValue(option)) : def;
92         }
93         if (def instanceof Long) {
94             return cmd.hasOption(option) ? (T) Long.valueOf(cmd.getOptionValue(option)) : def;
95         }
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);
100             } else {
101                 return (T) cmd.getParsedOptionValue(option);
102             }
103         }
104         return def;
105     }
106
107     private static void initLog(boolean silent, String logfile, Level loglvl) {
108         Logger.getRootLogger().getLoggerRepository().resetConfiguration();
109         LOG = LogFactory.getLog(Program.class);
110         if (!silent) {
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);
119         }
120         if (logfile != null) {
121             RollingFileAppender fa = new RollingFileAppender();
122             fa.setName("FileLogger");
123             fa.setFile(logfile);
124             fa.setLayout(new PatternLayout("%d %-5p [%c] %m%n"));
125             fa.setThreshold(loglvl);
126             fa.setMaximumFileSize(10000000);
127             fa.setAppend(true);
128             fa.setMaxBackupIndex(5);
129             fa.activateOptions();
130             // add appender to any Logger (here is root)
131             Logger.getRootLogger().addAppender(fa);
132         }
133         // repeat with all other desired appenders
134     }
135
136     public static void main(String[] args) {
137         CommandLineParser parser = new DefaultParser();
138         HelpFormatter formatter = new HelpFormatter();
139         CommandLine cmd = null;
140         try {
141             cmd = parser.parse(options, args);
142         } catch (ParseException e) {
143             System.out.println(e.getMessage());
144             printHelp(formatter);
145             System.exit(1);
146         }
147         if (cmd == null) {
148             printHelp(formatter);
149             System.exit(1);
150         }
151         try {
152             initLog(getOptionOrDefault(cmd, OPTION_SILENT_SHORT, false), null,
153                     getOptionOrDefault(cmd, OPTION_DEBUG_SHORT, false) ? Level.DEBUG : Level.INFO);
154         } catch (ParseException e2) {
155
156         }
157         switch (cmd.getOptionValue("c")) {
158         case CMD_INITDB:
159             try {
160                 cmd_init_db(cmd);
161             } catch (Exception e1) {
162                 exit(e1);
163             }
164             break;
165         case CMD_CLEAR_DB:
166             try {
167                 cmd_clear_db(cmd);
168             } catch (Exception e1) {
169                 exit(e1);
170             }
171             break;
172         case CMD_CREATE_PLUGIN_INIT_FILE:
173             try {
174                 String of = getOptionOrDefault(cmd, "of", null);
175                 if (of == null) {
176                     throw new Exception("please add the parameter output-file");
177                 }
178                 MavenDatabasePluginInitFile.create(Release.CURRENT_RELEASE, of);
179             } catch (Exception e) {
180                 exit(e);
181             }
182             break;
183         case CMD_IMPORT:
184             try {
185                 cmd_dbimport(cmd);
186             } catch (Exception e1) {
187                 exit(e1);
188             }
189             break;
190         case CMD_EXPORT:
191             try {
192                 cmd_dbexport(cmd);
193             } catch (Exception e) {
194                 exit(e);
195             }
196             break;
197         case CMD_LIST_VERSION:
198             cmd_listversion();
199             break;
200         default:
201             printHelp(formatter);
202             break;
203         }
204         System.exit(0);
205     }
206
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]));
212         }
213     }
214
215     private static void cmd_listversion() {
216
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()) {
221
222             System.out.println(String.format(format, r.getValue(),
223                     r.getDBSuffix() != null && r.getDBSuffix().length() > 1 ? r.getDBSuffix().substring(1) : ""));
224         }
225
226     }
227
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");
236         }
237         DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
238                 username, password, trustAll);
239         DataMigrationReport report = service.importData(filename, false);
240         LOG.info(report);
241         if(!report.completed()) {
242             throw new Exception("db import seems to be not executed completed");
243         }
244     }
245
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");
254         }
255         DataMigrationProviderImpl service = new DataMigrationProviderImpl(new HostInfo[] { HostInfo.parse(dbUrl) },
256                 username, password, trustAll);
257         DataMigrationReport report = service.exportData(filename);
258         LOG.info(report);
259         if(!report.completed()) {
260             throw new Exception("db export seems to be not executed completed");
261         }
262
263     }
264
265     private static void exit(Exception e) {
266         if (LOG != null) {
267             LOG.error("Error during execution: {}", e);
268         } else {
269             System.err.println(e);
270         }
271         System.exit(1);
272     }
273
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");
286         }
287     }
288
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");
304         }
305
306     }
307
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));
322         result.addOption(
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));
327
328         return result;
329     }
330
331     /**
332      * @param opt
333      * @param longOpt
334      * @param hasArg
335      * @param description
336      * @param required
337      * @return
338      */
339     private static Option createOption(String opt, String longOpt, boolean hasArg, String description,
340             boolean required) {
341         Option o = new Option(opt, longOpt, hasArg, description);
342         o.setRequired(required);
343         return o;
344     }
345 }