Debian Codegraph @

src/main/org/h2/tools/CreateCluster.java

raw
1 /*
2 * Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0,
3 * and the EPL 1.0 (https://h2database.com/html/license.html).
4 * Initial Developer: H2 Group
5 */
6 package org.h2.tools;
7
8 import java.io.IOException;
9 import java.io.PipedReader;
10 import java.io.PipedWriter;
11 import java.sql.ResultSet;
12 import java.sql.SQLException;
13 import java.sql.Statement;
14 import java.util.concurrent.ExecutionException;
15 import java.util.concurrent.ExecutorService;
16 import java.util.concurrent.Executors;
17 import java.util.concurrent.Future;
18 import org.h2.jdbc.JdbcConnection;
19 import org.h2.util.Tool;
20
21 /**
22 * Creates a cluster from a stand-alone database.
23 *
24 * Copies a database to another location if required.
25 */
26 public class CreateCluster extends Tool {
27
28 /**
29 * Options are case sensitive.
30 * <table>
31 * <caption>Supported options</caption>
32 * <tr><td>[-help] or [-?]</td>
33 * <td>Print the list of options</td></tr>
34 * <tr><td>[-urlSource "&lt;url&gt;"]</td>
35 * <td>The database URL of the source database (jdbc:h2:...)</td></tr>
36 * <tr><td>[-urlTarget "&lt;url&gt;"]</td>
37 * <td>The database URL of the target database (jdbc:h2:...)</td></tr>
38 * <tr><td>[-user &lt;user&gt;]</td>
39 * <td>The user name (default: sa)</td></tr>
40 * <tr><td>[-password &lt;pwd&gt;]</td>
41 * <td>The password</td></tr>
42 * <tr><td>[-serverList &lt;list&gt;]</td>
43 * <td>The comma separated list of host names or IP addresses</td></tr>
44 * </table>
45 *
46 * @param args the command line arguments
47 * @throws SQLException on failure
48 */
49 public static void main(String... args) throws SQLException {
50 new CreateCluster().runTool(args);
51 }
52
53 @Override
54 public void runTool(String... args) throws SQLException {
55 String urlSource = null;
56 String urlTarget = null;
57 String user = "";
58 String password = "";
59 String serverList = null;
60 for (int i = 0; args != null && i < args.length; i++) {
61 String arg = args[i];
62 if (arg.equals("-urlSource")) {
63 urlSource = args[++i];
64 } else if (arg.equals("-urlTarget")) {
65 urlTarget = args[++i];
66 } else if (arg.equals("-user")) {
67 user = args[++i];
68 } else if (arg.equals("-password")) {
69 password = args[++i];
70 } else if (arg.equals("-serverList")) {
71 serverList = args[++i];
72 } else if (arg.equals("-help") || arg.equals("-?")) {
73 showUsage();
74 return;
75 } else {
76 showUsageAndThrowUnsupportedOption(arg);
77 }
78 }
79 if (urlSource == null || urlTarget == null || serverList == null) {
80 showUsage();
81 throw new SQLException("Source URL, target URL, or server list not set");
82 }
83 process(urlSource, urlTarget, user, password, serverList);
84 }
85
86 /**
87 * Creates a cluster.
88 *
89 * @param urlSource the database URL of the original database
90 * @param urlTarget the database URL of the copy
91 * @param user the user name
92 * @param password the password
93 * @param serverList the server list
94 * @throws SQLException on failure
95 */
96 public void execute(String urlSource, String urlTarget,
97 String user, String password, String serverList) throws SQLException {
98 process(urlSource, urlTarget, user, password, serverList);
99 }
100
101 private static void process(String urlSource, String urlTarget,
102 String user, String password, String serverList) throws SQLException {
103 // use cluster='' so connecting is possible
104 // even if the cluster is enabled
105 try (JdbcConnection connSource = new JdbcConnection(urlSource + ";CLUSTER=''", null, user, password, false);
106 Statement statSource = connSource.createStatement()) {
107 // enable the exclusive mode and close other connections,
108 // so that data can't change while restoring the second database
109 statSource.execute("SET EXCLUSIVE 2");
110 try {
111 performTransfer(statSource, urlTarget, user, password, serverList);
112 } finally {
113 // switch back to the regular mode
114 statSource.execute("SET EXCLUSIVE FALSE");
115 }
116 }
117 }
118
119 private static void performTransfer(Statement statSource, String urlTarget, String user, String password,
120 String serverList) throws SQLException {
121
122 // Delete the target database first.
123 try (JdbcConnection connTarget = new JdbcConnection(urlTarget + ";CLUSTER=''", null, user, password, false);
124 Statement statTarget = connTarget.createStatement()) {
125 statTarget.execute("DROP ALL OBJECTS DELETE FILES");
126 }
127
128 try (PipedReader pipeReader = new PipedReader()) {
129 Future<?> threadFuture = startWriter(pipeReader, statSource);
130
131 // Read data from pipe reader, restore on target.
132 try (JdbcConnection connTarget = new JdbcConnection(urlTarget, null, user, password, false);
133 Statement statTarget = connTarget.createStatement()) {
134 RunScript.execute(connTarget, pipeReader);
135
136 // Check if the writer encountered any exception
137 try {
138 threadFuture.get();
139 } catch (ExecutionException ex) {
140 throw new SQLException(ex.getCause());
141 } catch (InterruptedException ex) {
142 throw new SQLException(ex);
143 }
144
145 // set the cluster to the serverList on both databases
146 statSource.executeUpdate("SET CLUSTER '" + serverList + "'");
147 statTarget.executeUpdate("SET CLUSTER '" + serverList + "'");
148 }
149 } catch (IOException ex) {
150 throw new SQLException(ex);
151 }
152 }
153
154 private static Future<?> startWriter(final PipedReader pipeReader,
155 final Statement statSource) throws IOException {
156 final ExecutorService thread = Executors.newFixedThreadPool(1);
157 final PipedWriter pipeWriter = new PipedWriter(pipeReader);
158 // Since exceptions cannot be thrown across thread boundaries, return
159 // the task's future so we can check manually
160 Future<?> threadFuture = thread.submit(() -> {
161 // If the creation of the piped writer fails, the reader will
162 // throw an IOException as soon as read() is called: IOException
163 // - if the pipe is broken, unconnected, closed, or an I/O error
164 // occurs. The reader's IOException will then trigger the
165 // finally{} that releases exclusive mode on the source DB.
166 try (PipedWriter writer = pipeWriter;
167 final ResultSet rs = statSource.executeQuery("SCRIPT")) {
168 while (rs.next()) {
169 writer.write(rs.getString(1) + "\n");
170 }
171 } catch (SQLException | IOException ex) {
172 throw new IllegalStateException("Producing script from the source DB is failing.", ex);
173 }
174 });
175
176 thread.shutdown();
177
178 return threadFuture;
179 }
180
181 }