View Javadoc
1   /*
2    * Copyright (C) 2016, Google Inc.
3    * and other copyright owners as documented in the project's IP log.
4    *
5    * This program and the accompanying materials are made available
6    * under the terms of the Eclipse Distribution License v1.0 which
7    * accompanies this distribution, is reproduced below, and is
8    * available at http://www.eclipse.org/org/documents/edl-v10.php
9    *
10   * All rights reserved.
11   *
12   * Redistribution and use in source and binary forms, with or
13   * without modification, are permitted provided that the following
14   * conditions are met:
15   *
16   * - Redistributions of source code must retain the above copyright
17   *   notice, this list of conditions and the following disclaimer.
18   *
19   * - Redistributions in binary form must reproduce the above
20   *   copyright notice, this list of conditions and the following
21   *   disclaimer in the documentation and/or other materials provided
22   *   with the distribution.
23   *
24   * - Neither the name of the Eclipse Foundation, Inc. nor the
25   *   names of its contributors may be used to endorse or promote
26   *   products derived from this software without specific prior
27   *   written permission.
28   *
29   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
30   * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
31   * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
32   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
33   * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
34   * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
35   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
36   * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
37   * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
38   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
39   * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
40   * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
41   * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
42   */
43  
44  package org.eclipse.jgit.internal.ketch;
45  
46  import static org.eclipse.jgit.internal.ketch.KetchReplica.CommitMethod.ALL_REFS;
47  import static org.eclipse.jgit.internal.ketch.KetchReplica.CommitMethod.TXN_COMMITTED;
48  import static org.eclipse.jgit.lib.RefDatabase.ALL;
49  import static org.eclipse.jgit.transport.ReceiveCommand.Result.OK;
50  import static org.eclipse.jgit.transport.ReceiveCommand.Result.REJECTED_OTHER_REASON;
51  
52  import java.io.IOException;
53  import java.text.MessageFormat;
54  import java.util.ArrayList;
55  import java.util.Collection;
56  import java.util.List;
57  import java.util.Map;
58  
59  import org.eclipse.jgit.internal.storage.reftree.RefTreeDatabase;
60  import org.eclipse.jgit.lib.BatchRefUpdate;
61  import org.eclipse.jgit.lib.NullProgressMonitor;
62  import org.eclipse.jgit.lib.Ref;
63  import org.eclipse.jgit.lib.RefDatabase;
64  import org.eclipse.jgit.lib.Repository;
65  import org.eclipse.jgit.revwalk.RevWalk;
66  import org.eclipse.jgit.transport.ReceiveCommand;
67  import org.eclipse.jgit.util.time.MonotonicClock;
68  import org.eclipse.jgit.util.time.ProposedTimestamp;
69  
70  /** Ketch replica running on the same system as the {@link KetchLeader}. */
71  public class LocalReplica extends KetchReplica {
72  	/**
73  	 * Configure a local replica.
74  	 *
75  	 * @param leader
76  	 *            instance this replica follows.
77  	 * @param name
78  	 *            unique-ish name identifying this replica for debugging.
79  	 * @param cfg
80  	 *            how Ketch should treat the local system.
81  	 */
82  	public LocalReplica(KetchLeader leader, String name, ReplicaConfig cfg) {
83  		super(leader, name, cfg);
84  	}
85  
86  	@Override
87  	protected String describeForLog() {
88  		return String.format("%s (leader)", getName()); //$NON-NLS-1$
89  	}
90  
91  	/**
92  	 * Initializes local replica by reading accepted and committed references.
93  	 * <p>
94  	 * Loads accepted and committed references from the reference database of
95  	 * the local replica and stores their current ObjectIds in memory.
96  	 *
97  	 * @param repo
98  	 *            repository to initialize state from.
99  	 * @throws IOException
100 	 *             cannot read repository state.
101 	 */
102 	void initialize(Repository repo) throws IOException {
103 		RefDatabase refdb = repo.getRefDatabase();
104 		if (refdb instanceof RefTreeDatabase) {
105 			RefTreeDatabase treeDb = (RefTreeDatabase) refdb;
106 			String txnNamespace = getSystem().getTxnNamespace();
107 			if (!txnNamespace.equals(treeDb.getTxnNamespace())) {
108 				throw new IOException(MessageFormat.format(
109 						KetchText.get().mismatchedTxnNamespace,
110 						txnNamespace, treeDb.getTxnNamespace()));
111 			}
112 			refdb = treeDb.getBootstrap();
113 		}
114 		initialize(refdb.exactRef(
115 				getSystem().getTxnAccepted(),
116 				getSystem().getTxnCommitted()));
117 	}
118 
119 	@Override
120 	protected void startPush(final ReplicaPushRequest req) {
121 		getSystem().getExecutor().execute(new Runnable() {
122 			@Override
123 			public void run() {
124 				MonotonicClock clk = getSystem().getClock();
125 				try (Repository git = getLeader().openRepository();
126 						ProposedTimestamp ts = clk.propose()) {
127 					try {
128 						update(git, req, ts);
129 						req.done(git);
130 					} catch (Throwable err) {
131 						req.setException(git, err);
132 					}
133 				} catch (IOException err) {
134 					req.setException(null, err);
135 				}
136 			}
137 		});
138 	}
139 
140 	@Override
141 	protected void blockingFetch(Repository repo, ReplicaFetchRequest req)
142 			throws IOException {
143 		throw new IOException(KetchText.get().cannotFetchFromLocalReplica);
144 	}
145 
146 	private void update(Repository git, ReplicaPushRequest req,
147 			ProposedTimestamp ts) throws IOException {
148 		RefDatabase refdb = git.getRefDatabase();
149 		CommitMethod method = getCommitMethod();
150 
151 		// Local replica probably uses RefTreeDatabase, the request should
152 		// be only for the txnNamespace, so drop to the bootstrap layer.
153 		if (refdb instanceof RefTreeDatabase) {
154 			if (!isOnlyTxnNamespace(req.getCommands())) {
155 				return;
156 			}
157 
158 			refdb = ((RefTreeDatabase) refdb).getBootstrap();
159 			method = TXN_COMMITTED;
160 		}
161 
162 		BatchRefUpdate batch = refdb.newBatchUpdate();
163 		batch.addProposedTimestamp(ts);
164 		batch.setRefLogIdent(getSystem().newCommitter(ts));
165 		batch.setRefLogMessage("ketch", false); //$NON-NLS-1$
166 		batch.setAllowNonFastForwards(true);
167 
168 		// RefDirectory updates multiple references sequentially.
169 		// Run everything else first, then accepted (if present),
170 		// then committed (if present). This ensures an earlier
171 		// failure will not update these critical references.
172 		ReceiveCommand accepted = null;
173 		ReceiveCommand committed = null;
174 		for (ReceiveCommand cmd : req.getCommands()) {
175 			String name = cmd.getRefName();
176 			if (name.equals(getSystem().getTxnAccepted())) {
177 				accepted = cmd;
178 			} else if (name.equals(getSystem().getTxnCommitted())) {
179 				committed = cmd;
180 			} else {
181 				batch.addCommand(cmd);
182 			}
183 		}
184 		if (committed != null && method == ALL_REFS) {
185 			Map<String, Ref> refs = refdb.getRefs(ALL);
186 			batch.addCommand(prepareCommit(git, refs, committed.getNewId()));
187 		}
188 		if (accepted != null) {
189 			batch.addCommand(accepted);
190 		}
191 		if (committed != null) {
192 			batch.addCommand(committed);
193 		}
194 
195 		try (RevWalk rw = new RevWalk(git)) {
196 			batch.execute(rw, NullProgressMonitor.INSTANCE);
197 		}
198 
199 		// KetchReplica only cares about accepted and committed in
200 		// advertisement. If they failed, store the current values
201 		// back in the ReplicaPushRequest.
202 		List<String> failed = new ArrayList<>(2);
203 		checkFailed(failed, accepted);
204 		checkFailed(failed, committed);
205 		if (!failed.isEmpty()) {
206 			String[] arr = failed.toArray(new String[failed.size()]);
207 			req.setRefs(refdb.exactRef(arr));
208 		}
209 	}
210 
211 	private static void checkFailed(List<String> failed, ReceiveCommand cmd) {
212 		if (cmd != null && cmd.getResult() != OK) {
213 			failed.add(cmd.getRefName());
214 		}
215 	}
216 
217 	private boolean isOnlyTxnNamespace(Collection<ReceiveCommand> cmdList) {
218 		// Be paranoid and reject non txnNamespace names, this
219 		// is a programming error in Ketch that should not occur.
220 
221 		String txnNamespace = getSystem().getTxnNamespace();
222 		for (ReceiveCommand cmd : cmdList) {
223 			if (!cmd.getRefName().startsWith(txnNamespace)) {
224 				cmd.setResult(REJECTED_OTHER_REASON,
225 						MessageFormat.format(
226 								KetchText.get().outsideTxnNamespace,
227 								cmd.getRefName(), txnNamespace));
228 				ReceiveCommand.abort(cmdList);
229 				return false;
230 			}
231 		}
232 		return true;
233 	}
234 }