/
SymmetricAdmin.java
848 lines (753 loc) · 34.6 KB
/
SymmetricAdmin.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
/**
* Licensed to JumpMind Inc under one or more contributor
* license agreements. See the NOTICE file distributed
* with this work for additional information regarding
* copyright ownership. JumpMind Inc licenses this file
* to you under the GNU General Public License, version 3.0 (GPLv3)
* (the "License"); you may not use this file except in compliance
* with the License.
*
* You should have received a copy of the GNU General Public License,
* version 3.0 (GPLv3) along with this library; if not, see
* <http://www.gnu.org/licenses/>.
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jumpmind.symmetric;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Properties;
import java.util.Scanner;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jumpmind.db.model.Table;
import org.jumpmind.exception.IoException;
import org.jumpmind.properties.TypedProperties;
import org.jumpmind.security.ISecurityService;
import org.jumpmind.security.SecurityConstants;
import org.jumpmind.security.SecurityServiceFactory;
import org.jumpmind.security.SecurityServiceFactory.SecurityServiceType;
import org.jumpmind.symmetric.common.ParameterConstants;
import org.jumpmind.symmetric.model.Node;
import org.jumpmind.symmetric.model.TriggerHistory;
import org.jumpmind.symmetric.service.IDataExtractorService;
import org.jumpmind.symmetric.service.IDataLoaderService;
import org.jumpmind.symmetric.service.IDataService;
import org.jumpmind.symmetric.service.IPurgeService;
import org.jumpmind.symmetric.service.IRegistrationService;
import org.jumpmind.symmetric.service.ITriggerRouterService;
import org.jumpmind.symmetric.util.ModuleException;
import org.jumpmind.symmetric.util.ModuleManager;
import org.jumpmind.util.AppUtils;
import org.jumpmind.util.JarBuilder;
import org.jumpmind.util.ZipBuilder;
/**
* Perform administration tasks with SymmetricDS.
*/
public class SymmetricAdmin extends AbstractCommandLauncher {
@SuppressWarnings("unused")
private static final Log log = LogFactory.getLog(SymmetricAdmin.class);
private static final String CMD_LIST_ENGINES = "list-engines";
private static final String CMD_RELOAD_NODE = "reload-node";
private static final String CMD_RELOAD_TABLE = "reload-table";
private static final String CMD_EXPORT_BATCH = "export-batch";
private static final String CMD_IMPORT_BATCH = "import-batch";
private static final String CMD_RUN_JOB = "run-job";
private static final String CMD_RUN_PURGE = "run-purge";
private static final String CMD_ENCRYPT_TEXT = "encrypt-text";
private static final String CMD_OBFUSCATE_TEXT = "obfuscate-text";
private static final String CMD_CREATE_WAR = "create-war";
private static final String CMD_CREATE_SYM_TABLES = "create-sym-tables";
private static final String CMD_EXPORT_SYM_TABLES = "export-sym-tables";
private static final String CMD_OPEN_REGISTRATION = "open-registration";
private static final String CMD_REMOVE_NODE = "remove-node";
private static final String CMD_SYNC_TRIGGERS = "sync-triggers";
private static final String CMD_DROP_TRIGGERS = "drop-triggers";
private static final String CMD_EXPORT_PROPERTIES = "export-properties";
private static final String CMD_UNINSTALL = "uninstall";
private static final String CMD_MODULE = "module";
private static final String CMD_SEND_SQL = "send-sql";
private static final String CMD_SEND_SCRIPT = "send-script";
private static final String CMD_SEND_SCHEMA = "send-schema";
private static final String CMD_BACKUP_FILE_CONFIGURATION = "backup-config";
private static final String CMD_RESTORE_FILE_CONFIGURATION = "restore-config";
private static final String[] NO_ENGINE_REQUIRED = { CMD_EXPORT_PROPERTIES, CMD_ENCRYPT_TEXT, CMD_OBFUSCATE_TEXT, CMD_LIST_ENGINES, CMD_MODULE, CMD_BACKUP_FILE_CONFIGURATION, CMD_RESTORE_FILE_CONFIGURATION };
private static final String OPTION_NODE = "node";
private static final String OPTION_CATALOG = "catalog";
private static final String OPTION_SCHEMA = "schema";
private static final String OPTION_WHERE = "where";
private static final String OPTION_FORCE = "force";
private static final String OPTION_OUT = "out";
private static final String OPTION_NODE_GROUP = "node-group";
private static final String OPTION_REVERSE = "reverse";
private static final String OPTION_IN = "in";
private static final int WIDTH = 120;
private static final int PAD = 3;
public SymmetricAdmin(String app, String argSyntax, String messageKeyPrefix) {
super(app, argSyntax, messageKeyPrefix);
}
public static void main(String[] args) throws Exception {
new SymmetricAdmin("symadmin", "<subcommand> [options] [args]", "SymAdmin.Option.")
.execute(args);
}
@Override
protected boolean printHelpIfNoOptionsAreProvided() {
return true;
}
@Override
protected boolean requiresPropertiesFile(CommandLine line) {
String[] args = line.getArgs();
if (args.length >= 1) {
String cmd = args[0];
return !ArrayUtils.contains(NO_ENGINE_REQUIRED, cmd);
}
return true;
}
@Override
protected void printHelp(CommandLine line, Options options) {
String[] args = line.getArgs();
if (args.length > 1 && args[0].equals(HELP)) {
printHelpCommand(line);
} else {
System.out.println(app + " version " + Version.version());
System.out.println("Perform administration tasks with SymmetricDS.\n");
System.out
.println("Usage: symadmin <subcommand> --engine [engine.name] [options] [args]");
System.out
.println(" symadmin <subcommand> --properties [properties file] [options] [args]");
System.out
.println("\nType 'symadmin help <subcommand>' for help on a specific subcommand.\n");
System.out.println("Available subcommands:");
PrintWriter pw = new PrintWriter(System.out);
printHelpLine(pw, CMD_LIST_ENGINES);
printHelpLine(pw, CMD_OPEN_REGISTRATION);
printHelpLine(pw, CMD_REMOVE_NODE);
printHelpLine(pw, CMD_RELOAD_NODE);
printHelpLine(pw, CMD_RELOAD_TABLE);
printHelpLine(pw, CMD_EXPORT_BATCH);
printHelpLine(pw, CMD_IMPORT_BATCH);
printHelpLine(pw, CMD_RUN_JOB);
printHelpLine(pw, CMD_RUN_PURGE);
printHelpLine(pw, CMD_ENCRYPT_TEXT);
printHelpLine(pw, CMD_OBFUSCATE_TEXT);
printHelpLine(pw, CMD_CREATE_WAR);
printHelpLine(pw, CMD_CREATE_SYM_TABLES);
printHelpLine(pw, CMD_EXPORT_SYM_TABLES);
printHelpLine(pw, CMD_SYNC_TRIGGERS);
printHelpLine(pw, CMD_DROP_TRIGGERS);
printHelpLine(pw, CMD_EXPORT_PROPERTIES);
printHelpLine(pw, CMD_SEND_SQL);
printHelpLine(pw, CMD_SEND_SCHEMA);
printHelpLine(pw, CMD_SEND_SCRIPT);
printHelpLine(pw, CMD_BACKUP_FILE_CONFIGURATION);
printHelpLine(pw, CMD_RESTORE_FILE_CONFIGURATION);
printHelpLine(pw, CMD_UNINSTALL);
printHelpLine(pw, CMD_MODULE);
pw.flush();
}
}
private void printHelpLine(PrintWriter pw, String cmd) {
String text = StringUtils.rightPad(" " + cmd, 23, " ")
+ Message.get("SymAdmin.Cmd." + cmd);
new HelpFormatter().printWrapped(pw, 79, 25, text);
}
private void printHelpCommand(CommandLine line) {
String[] args = line.getArgs();
if (args.length > 1) {
String cmd = args[1];
HelpFormatter format = new HelpFormatter();
PrintWriter writer = new PrintWriter(System.out);
Options options = new Options();
if (! Message.containsKey("SymAdmin.Usage." + cmd)) {
System.err.println("ERROR: no help text for subcommand '" + cmd + "' was found.");
System.err.println("For a list of subcommands, use " + app + " --" + HELP + "\n");
return;
}
format.printWrapped(writer, WIDTH,
"Usage: " + app + " " + cmd + " " + Message.get("SymAdmin.Usage." + cmd) + "\n");
format.printWrapped(writer, WIDTH, Message.get("SymAdmin.Help." + cmd));
if (cmd.equals(CMD_SEND_SQL) || cmd.equals(CMD_SEND_SCHEMA)
|| cmd.equals(CMD_RELOAD_TABLE) || cmd.equals(CMD_SEND_SCRIPT)) {
addOption(options, "n", OPTION_NODE, true);
addOption(options, "g", OPTION_NODE_GROUP, true);
}
if (cmd.equals(CMD_RELOAD_TABLE) || cmd.equals(CMD_SYNC_TRIGGERS) || cmd.equals(CMD_SEND_SQL) || cmd.equals(CMD_SEND_SCHEMA)) {
addOption(options, "c", OPTION_CATALOG, true);
addOption(options, "s", OPTION_SCHEMA, true);
}
if (cmd.equals(CMD_RELOAD_TABLE)) {
addOption(options, "w", OPTION_WHERE, true);
}
if (cmd.equals(CMD_SYNC_TRIGGERS)) {
addOption(options, "o", OPTION_OUT, true);
addOption(options, "f", OPTION_FORCE, false);
}
if (cmd.equals(CMD_RELOAD_NODE)) {
addOption(options, "r", OPTION_REVERSE, false);
}
if (cmd.equals(CMD_REMOVE_NODE)) {
addOption(options, "n", OPTION_NODE, true);
}
if(cmd.equals(CMD_BACKUP_FILE_CONFIGURATION)) {
addOption(options, "o", OPTION_OUT, true);
}
if(cmd.equals(CMD_RESTORE_FILE_CONFIGURATION)) {
addOption(options, "i", OPTION_IN, true);
}
if (options.getOptions().size() > 0) {
format.printWrapped(writer, WIDTH, "\nOptions:");
format.printOptions(writer, WIDTH, options, PAD, PAD);
}
if (!ArrayUtils.contains(NO_ENGINE_REQUIRED, cmd)) {
format.printWrapped(writer, WIDTH, "\nEngine options:");
options = new Options();
super.buildOptions(options);
format.printOptions(writer, WIDTH, options, PAD, PAD);
format.printWrapped(writer, WIDTH, "\nCrypto options:");
options = new Options();
buildCryptoOptions(options);
format.printOptions(writer, WIDTH, options, PAD, PAD);
}
writer.flush();
}
}
@Override
protected void buildOptions(Options options) {
super.buildOptions(options);
addOption(options, "n", OPTION_NODE, true);
addOption(options, "g", OPTION_NODE_GROUP, true);
addOption(options, "c", OPTION_CATALOG, true);
addOption(options, "s", OPTION_SCHEMA, true);
addOption(options, "w", OPTION_WHERE, true);
addOption(options, "f", OPTION_FORCE, false);
addOption(options, "o", OPTION_OUT, true);
addOption(options, "r", OPTION_REVERSE, false);
addOption(options, "i", OPTION_IN, true);
buildCryptoOptions(options);
}
@Override
protected boolean executeWithOptions(CommandLine line) throws Exception {
List<String> args = line.getArgList();
String cmd = args.remove(0);
configureCrypto(line);
if (cmd.equals(CMD_EXPORT_PROPERTIES)) {
exportDefaultProperties(line, args);
return true;
} else if (cmd.equals(CMD_LIST_ENGINES)) {
listEngines(line, args);
return true;
} else if (cmd.equals(CMD_CREATE_WAR)) {
generateWar(line, args);
return true;
} else if (cmd.equals(CMD_EXPORT_SYM_TABLES)) {
exportSymTables(line, args);
return true;
} else if (cmd.equals(CMD_RUN_JOB)) {
runJob(line, args);
return true;
} else if (cmd.equals(CMD_RUN_PURGE)) {
runPurge(line, args);
return true;
} else if (cmd.equals(CMD_OPEN_REGISTRATION)) {
openRegistration(line, args);
return true;
} else if(cmd.equals(CMD_REMOVE_NODE)) {
removeNode(line, args);
return true;
} else if (cmd.equals(CMD_RELOAD_NODE)) {
reloadNode(line, args);
return true;
} else if (cmd.equals(CMD_EXPORT_BATCH)) {
exportBatch(line, args);
return true;
} else if (cmd.equals(CMD_SYNC_TRIGGERS)) {
syncTrigger(line, args);
return true;
} else if (cmd.equals(CMD_DROP_TRIGGERS)) {
dropTrigger(line, args);
return true;
} else if (cmd.equals(CMD_CREATE_SYM_TABLES)) {
createSymTables();
return true;
} else if (cmd.equals(CMD_IMPORT_BATCH)) {
importBatch(line, args);
return true;
} else if (cmd.equals(CMD_ENCRYPT_TEXT)) {
encryptText(line, args);
return true;
} else if (cmd.equals(CMD_OBFUSCATE_TEXT)) {
obfuscateText(line, args);
return true;
} else if (cmd.equals(CMD_SEND_SQL)) {
sendSql(line, args);
return true;
} else if (cmd.equals(CMD_UNINSTALL)) {
uninstall(line, args);
return true;
} else if (cmd.equals(CMD_RELOAD_TABLE)) {
reloadTable(line, args);
return true;
} else if (cmd.equals(CMD_SEND_SCHEMA)) {
sendSchema(line, args);
return true;
} else if (cmd.equals(CMD_SEND_SCRIPT)) {
sendScript(line, args);
return true;
} else if (cmd.equals(CMD_MODULE)) {
module(line, args);
return true;
} else if (cmd.equals(CMD_BACKUP_FILE_CONFIGURATION)) {
backup(line, args);
return true;
} else if (cmd.equals(CMD_RESTORE_FILE_CONFIGURATION)) {
restore(line, args);
return true;
} else {
throw new ParseException("ERROR: no subcommand '" + cmd + "' was found.");
}
}
private String popArg(List<String> args, String argName) {
if (args.size() == 0) {
System.out.println("ERROR: Expected argument for: " + argName);
System.exit(1);
}
return args.remove(0);
}
private void listEngines(CommandLine line, List<String> args) {
System.out.println("Engines directory is " + new File(getEnginesDir()).getAbsolutePath());
System.out.println("The following engines and properties files are available:");
int count = 0;
File[] files = findEnginePropertiesFiles();
for (File file : files) {
Properties properties = new Properties();
try(FileInputStream is = new FileInputStream(file)) {
properties.load(is);
String name = properties.getProperty(ParameterConstants.ENGINE_NAME);
System.out.println(name + " -> " + file.getAbsolutePath());
count++;
} catch (IOException ex) {
}
}
System.out.println(count + " engines returned");
}
private void runJob(CommandLine line, List<String> args) throws Exception{
String jobName = popArg(args, "job name");
if (jobName.equals("pull")) {
getSymmetricEngine().pull();
getSymmetricEngine().getNodeCommunicationService().stop();
} else if (jobName.equals("push")) {
getSymmetricEngine().push();
getSymmetricEngine().getNodeCommunicationService().stop();
} else if (jobName.equals("route")) {
getSymmetricEngine().route();
} else if (jobName.equals("purge")) {
getSymmetricEngine().purge();
} else if (jobName.equals("heartbeat")) {
getSymmetricEngine().heartbeat(false);
} else {
throw new ParseException("ERROR: no job named '" + jobName + "' was found.");
}
}
private void runPurge(CommandLine line, List<String> args) {
IPurgeService purgeService = getSymmetricEngine().getPurgeService();
boolean all = args.contains("all") || args.size() == 0;
if (args.contains("outgoing") || all) {
purgeService.purgeOutgoing(true);
}
if (args.contains("incoming") || all) {
purgeService.purgeIncoming(true);
}
}
private void exportBatch(CommandLine line, List<String> args) throws Exception {
IDataExtractorService dataExtractorService = getSymmetricEngine().getDataExtractorService();
String nodeId = popArg(args, "Node ID");
String batchId = popArg(args, "Batch ID");
OutputStreamWriter writer = getWriter(args);
dataExtractorService.extractBatchRange(writer, nodeId, Long.valueOf(batchId),
Long.valueOf(batchId));
writer.close();
}
private void importBatch(CommandLine line, List<String> args) throws Exception {
IDataLoaderService service = getSymmetricEngine().getDataLoaderService();
InputStream in = null;
if (args.size() == 0) {
in = System.in;
} else {
in = new FileInputStream(args.get(0));
}
service.loadDataFromPush(getSymmetricEngine().getNodeService().findIdentity(), in,
System.out);
System.out.flush();
in.close();
}
private void encryptText(CommandLine line, List<String> args) {
String plainText;
if(args.size() != 0) {
plainText = popArg(args, "Text");
} else {
@SuppressWarnings("resource")
Scanner textScanner = new Scanner(System.in);
System.out.print("Enter Text: ");
plainText = textScanner.next();
}
ISecurityService service = createSecurityService();
System.out.println(SecurityConstants.PREFIX_ENC + service.encrypt(plainText));
}
private ISecurityService createSecurityService() {
TypedProperties properties = ClientSymmetricEngine.createTypedPropertiesFactory(propertiesFile, new Properties()).reload();
return SecurityServiceFactory.create(SecurityServiceType.SERVER, properties);
}
private void obfuscateText(CommandLine line, List<String> args) {
String plainText = popArg(args, "Text");
ISecurityService service = createSecurityService();
System.out.println(SecurityConstants.PREFIX_OBF + service.obfuscate(plainText));
}
private void openRegistration(CommandLine line, List<String> args) {
String nodeGroupId = popArg(args, "Node Group ID");
String externalId = popArg(args, "External ID");
IRegistrationService registrationService = getSymmetricEngine().getRegistrationService();
registrationService.openRegistration(nodeGroupId, externalId);
System.out.println(String.format(
"Opened registration for node group of '%s' external ID of '%s'", nodeGroupId,
externalId));
}
private void removeNode(CommandLine line, List<String> args) {
String node = line.getOptionValue(OPTION_NODE);
getSymmetricEngine().removeAndCleanupNode(node);
System.out.println(String.format("Removed node '%s' from engine '%s'", node, getSymmetricEngine().getEngineName()));
}
private void reloadNode(CommandLine line, List<String> args) {
String nodeId = popArg(args, "Node ID");
boolean reverse = line.hasOption(OPTION_REVERSE);
IDataService dataService = getSymmetricEngine().getDataService();
String message = dataService.reloadNode(nodeId, reverse, "symadmin");
System.out.println(message);
}
private void backup(CommandLine line, List<String> args) throws IOException {
String filename = line.getOptionValue(OPTION_OUT);
if(filename == null) {
filename = "symmetric-file-configuration-" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".zip";
}
File jarFile = null;
if(filename != null) {
jarFile = new File(filename);
if (jarFile.getParentFile() != null) {
jarFile.getParentFile().mkdirs();
}
}
List<String> listOfDirs = new ArrayList<String>();
listOfDirs.add(AbstractCommandLauncher.getEnginesDir());
listOfDirs.add(AppUtils.getSymHome() + "/conf");
listOfDirs.add(AppUtils.getSymHome() + "/patches");
listOfDirs.add(AppUtils.getSymHome() + "/security");
String parentDir = new File(DEFAULT_SERVER_PROPERTIES).getParent();
if(parentDir != null) {
if(listOfDirs.indexOf(parentDir) < 0) {
// Need to add DEFAULT_SERVER_PROPERTIES to list of files to back up
// because the file is specified outside of the SymmetricDS installation
listOfDirs.add(DEFAULT_SERVER_PROPERTIES);
}
}
File[] arrayOfFile = new File[listOfDirs.size()];
for(int i = 0; i < listOfDirs.size(); i++) {
arrayOfFile[i] = new File(listOfDirs.get(i));
}
System.out.println("Backing up files to " + filename);
try {
ZipBuilder builder = new ZipBuilder(new File(AppUtils.getSymHome()), jarFile, arrayOfFile);
builder.build();
} catch (Exception e) {
throw new IoException("Failed to backup configuration files into archive", e);
}
}
private void restore(CommandLine line, List<String> args) throws IOException {
String filename = line.getOptionValue(OPTION_IN);
if(filename == null) {
throw new IoException("Input filename must be specified");
}
try(FileInputStream finput = new FileInputStream(filename);ZipInputStream zip = new ZipInputStream(finput)) {
ZipEntry entry = null;
for (entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) {
if(entry.isDirectory()) {
continue;
}
System.out.println("Restoring " + entry.getName());
File fileToOpen = null;
File f = new File(entry.getName());
if(f.isAbsolute()) {
f.getParentFile().mkdirs();
fileToOpen = f;
} else {
fileToOpen = new File(AppUtils.getSymHome(), entry.getName());
}
try(FileOutputStream foutput = new FileOutputStream(fileToOpen)) {
final byte buffer[] = new byte[4096];
int readCount;
while ((readCount = zip.read(buffer, 0, buffer.length)) > 0) {
foutput.write(buffer, 0, readCount);
}
}
}
}
}
private void syncTrigger(CommandLine line, List<String> args) throws IOException {
boolean genAlways = line.hasOption(OPTION_FORCE);
String filename = line.getOptionValue(OPTION_OUT);
String catalogName = line.getOptionValue(OPTION_CATALOG);
String schemaName = line.getOptionValue(OPTION_SCHEMA);
File file = null;
if (filename != null) {
file = new File(filename);
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
}
ITriggerRouterService triggerService = getSymmetricEngine().getTriggerRouterService();
StringBuilder sqlBuffer = new StringBuilder();
if (args.size() == 0) {
triggerService.syncTriggers(sqlBuffer, genAlways);
} else {
for (String tablename : args) {
Table table = platform.getTableFromCache(catalogName, schemaName, tablename, true);
if (table != null) {
triggerService.syncTriggers(table, genAlways);
} else {
System.out.println("Unable to find table " + tablename);
}
}
}
if (file != null) {
FileUtils.writeStringToFile(file, sqlBuffer.toString(), Charset.defaultCharset(), false);
}
}
private void dropTrigger(CommandLine line, List<String> args) throws IOException {
ITriggerRouterService triggerService = getSymmetricEngine().getTriggerRouterService();
if (args.size() == 0) {
System.out.println("Dropping all triggers...");
triggerService.dropTriggers();
} else {
for (String tablename : args) {
System.out.println("Dropping trigger for table " + tablename);
Set<String> tables = new HashSet<String>();
tables.add(tablename);
triggerService.dropTriggers(tables);
}
}
}
private void generateWar(CommandLine line, List<String> args) throws Exception {
String warFileName = popArg(args, "Filename");
final File workingDirectory = new File(AppUtils.getSymHome() + "/.war");
FileUtils.deleteDirectory(workingDirectory);
FileUtils.copyDirectory(new File(AppUtils.getSymHome() + "/web"), workingDirectory);
FileUtils.copyDirectory(new File(AppUtils.getSymHome() + "/conf"), new File(workingDirectory, "WEB-INF/classes"));
if (propertiesFile != null && propertiesFile.exists()) {
FileUtils.copyFile(propertiesFile, new File(workingDirectory,
"WEB-INF/classes/symmetric.properties"));
}
JarBuilder builder = new JarBuilder(workingDirectory, new File(warFileName),
new File[] { workingDirectory }, Version.version());
builder.build();
FileUtils.deleteDirectory(workingDirectory);
}
private void exportSymTables(CommandLine line, List<String> args) throws IOException {
OutputStreamWriter os = getWriter(args);
os.write(getSymmetricEngine().getSymmetricDialect().getCreateSymmetricDDL());
os.close();
}
private void exportDefaultProperties(CommandLine line, List<String> args) throws IOException {
OutputStreamWriter os = getWriter(args);
BufferedReader is = new BufferedReader(new InputStreamReader(
SymmetricAdmin.class.getResourceAsStream("/symmetric-default.properties"),
Charset.defaultCharset()));
String str = is.readLine();
while (str != null) {
os.write(str);
os.write(System.getProperty("line.separator"));
str = is.readLine();
}
is.close();
os.close();
}
private void createSymTables() {
getSymmetricEngine().setupDatabase(true);
}
private void uninstall(CommandLine line, List<String> args) {
getSymmetricEngine().uninstall();
}
private void sendSql(CommandLine line, List<String> args) {
String tableName = popArg(args, "Table Name");
String sql = popArg(args, "SQL");
String catalogName = line.getOptionValue(OPTION_CATALOG);
String schemaName = line.getOptionValue(OPTION_SCHEMA);
for (Node node : getNodes(line)) {
System.out.println("Sending SQL to node '" + node.getNodeId() + "'");
getSymmetricEngine().getDataService().sendSQL(node.getNodeId(), catalogName,
schemaName, tableName, sql);
}
}
private void reloadTable(CommandLine line, List<String> args) {
String catalogName = line.getOptionValue(OPTION_CATALOG);
String schemaName = line.getOptionValue(OPTION_SCHEMA);
if (args.size() == 0) {
System.out.println("ERROR: Expected argument for: Table Name");
System.exit(1);
}
for (String tableName : args) {
for (Node node : getNodes(line)) {
System.out.println("Reloading table '" + tableName + "' to node '" + node.getNodeId() + "'");
if (line.hasOption(OPTION_WHERE)) {
System.out.println(getSymmetricEngine().getDataService().reloadTable(node.getNodeId(), catalogName,
schemaName, tableName, line.getOptionValue(OPTION_WHERE)));
} else {
System.out.println(getSymmetricEngine().getDataService().reloadTable(node.getNodeId(), catalogName,
schemaName, tableName));
}
}
}
}
private void sendSchema(CommandLine line, List<String> args) {
String catalog = line.getOptionValue(OPTION_CATALOG);
String schema = line.getOptionValue(OPTION_SCHEMA);
Collection<Node> nodes = getNodes(line);
if (args.size() == 0) {
for (TriggerHistory hist : engine.getTriggerRouterService().getActiveTriggerHistories()) {
for (Node node : nodes) {
if ((catalog == null || catalog.equals(hist.getSourceCatalogName())) &&
(schema == null || schema.equals(hist.getSourceSchemaName()))) {
getSymmetricEngine().getDataService().sendSchema(node.getNodeId(), hist.getSourceCatalogName(),
hist.getSourceSchemaName(), hist.getSourceTableName(), false);
}
}
}
} else {
for (String tableName : args) {
for (Node node : nodes) {
getSymmetricEngine().getDataService().sendSchema(node.getNodeId(), catalog,
schema, tableName, false);
}
}
}
}
private void sendScript(CommandLine line, List<String> args) throws Exception {
String scriptName = popArg(args, "Script Name");
String scriptData = FileUtils.readFileToString(new File(scriptName), Charset.defaultCharset());
for (Node node : getNodes(line)) {
System.out.println("Sending script to node '" + node.getNodeId() + "'");
getSymmetricEngine().getDataService().sendScript(node.getNodeId(), scriptData, false);
}
}
private Collection<Node> getNodes(CommandLine line) {
if (line.hasOption(OPTION_NODE_GROUP)) {
return getSymmetricEngine().getNodeService().findEnabledNodesFromNodeGroup(
line.getOptionValue(OPTION_NODE_GROUP));
} else if (line.hasOption(OPTION_NODE)) {
Collection<Node> nodes = new ArrayList<Node>();
String nodeId = line.getOptionValue(OPTION_NODE);
Node node = getSymmetricEngine().getNodeService().findNode(nodeId);
if (node == null) {
System.out.println("ERROR: Unable to find node '" + nodeId + "'");
System.exit(1);
}
nodes.add(node);
return nodes;
} else {
System.out.println("ERROR: Must specify one option: " + OPTION_NODE + ", "
+ OPTION_NODE_GROUP);
System.exit(1);
}
return null;
}
private OutputStreamWriter getWriter(List<String> args) throws IOException {
OutputStreamWriter os = null;
if (args.size() == 0) {
os = new OutputStreamWriter(System.out);
} else {
File file = new File(args.get(0));
if (file.getParentFile() != null) {
file.getParentFile().mkdirs();
}
os = new FileWriter(file);
}
return os;
}
private void module(CommandLine line, List<String> args) throws Exception {
final String action = popArg(args, "Action");
final String moduleArgName = "Module";
try {
ModuleManager mgr = ModuleManager.getInstance();
if (action.equals("install")) {
mgr.install(popArg(args, moduleArgName));
} else if (action.equals("remove")) {
mgr.remove(popArg(args, moduleArgName));
} else if (action.equals("list-files")) {
String module = popArg(args, moduleArgName);
List<String> files = mgr.listFiles(module);
System.out.println("Files associated with module " + module + ":");
for (String file : files) {
System.out.println(file);
}
} else if (action.equals("list-deps")) {
String module = popArg(args, moduleArgName);
List<String> files = mgr.listDependencies(module);
System.out.println("Files associated with module " + module + ":");
for (String file : files) {
System.out.println(file);
}
} else if (action.equals("list")) {
List<String> modules = mgr.list();
System.out.println("Installed modules:");
if (modules.size() == 0) {
System.out.println("<none>");
} else {
for (String module : modules) {
System.out.println(module);
}
}
} else if (action.equals("list-all")) {
List<String> modules = mgr.listAll();
System.out.println("Available modules:");
for (String module : modules) {
System.out.println(module);
}
} else if (action.equals("upgrade")) {
System.out.println("Upgrading modules");
mgr.upgradeAll();
}
} catch (ModuleException e) {
if (!e.isLogged()) {
System.err.println("ERROR: " + e.getMessage());
}
System.exit(1);
}
}
}