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 java.util.concurrent.TimeUnit.SECONDS;
47  import static org.eclipse.jgit.internal.ketch.KetchConstants.TERM;
48  
49  import java.io.IOException;
50  import java.util.List;
51  import java.util.concurrent.TimeoutException;
52  
53  import org.eclipse.jgit.lib.CommitBuilder;
54  import org.eclipse.jgit.lib.ObjectId;
55  import org.eclipse.jgit.lib.ObjectInserter;
56  import org.eclipse.jgit.lib.Repository;
57  import org.eclipse.jgit.lib.TreeFormatter;
58  import org.eclipse.jgit.revwalk.RevCommit;
59  import org.eclipse.jgit.revwalk.RevWalk;
60  import org.eclipse.jgit.util.time.ProposedTimestamp;
61  import org.slf4j.Logger;
62  import org.slf4j.LoggerFactory;
63  
64  /**
65   * The initial {@link Round} for a leaderless repository, used to establish a
66   * leader.
67   */
68  class ElectionRound extends Round {
69  	private static final Logger log = LoggerFactory.getLogger(ElectionRound.class);
70  
71  	private long term;
72  
73  	ElectionRound(KetchLeader leader, LogIndex head) {
74  		super(leader, head);
75  	}
76  
77  	@Override
78  	void start() throws IOException {
79  		ObjectId id;
80  		try (Repository git = leader.openRepository();
81  				ProposedTimestamp ts = getSystem().getClock().propose();
82  				ObjectInserter inserter = git.newObjectInserter()) {
83  			id = bumpTerm(git, ts, inserter);
84  			inserter.flush();
85  			blockUntil(ts);
86  		}
87  		runAsync(id);
88  	}
89  
90  	@Override
91  	void success() {
92  		// Do nothing upon election, KetchLeader will copy the term.
93  	}
94  
95  	long getTerm() {
96  		return term;
97  	}
98  
99  	private ObjectId bumpTerm(Repository git, ProposedTimestamp ts,
100 			ObjectInserter inserter) throws IOException {
101 		CommitBuilder b = new CommitBuilder();
102 		if (!ObjectId.zeroId().equals(acceptedOldIndex)) {
103 			try (RevWalk rw = new RevWalk(git)) {
104 				RevCommit c = rw.parseCommit(acceptedOldIndex);
105 				if (getSystem().requireMonotonicLeaderElections()) {
106 					if (ts.read(SECONDS) < c.getCommitTime()) {
107 						throw new TimeIsUncertainException();
108 					}
109 				}
110 				b.setTreeId(c.getTree());
111 				b.setParentId(acceptedOldIndex);
112 				term = parseTerm(c.getFooterLines(TERM)) + 1;
113 			}
114 		} else {
115 			term = 1;
116 			b.setTreeId(inserter.insert(new TreeFormatter()));
117 		}
118 
119 		StringBuilder msg = new StringBuilder();
120 		msg.append(KetchConstants.TERM.getName())
121 				.append(": ") //$NON-NLS-1$
122 				.append(term);
123 
124 		String tag = leader.getSystem().newLeaderTag();
125 		if (tag != null && !tag.isEmpty()) {
126 			msg.append(' ').append(tag);
127 		}
128 
129 		b.setAuthor(leader.getSystem().newCommitter(ts));
130 		b.setCommitter(b.getAuthor());
131 		b.setMessage(msg.toString());
132 
133 		if (log.isDebugEnabled()) {
134 			log.debug("Trying to elect myself " + b.getMessage()); //$NON-NLS-1$
135 		}
136 		return inserter.insert(b);
137 	}
138 
139 	private static long parseTerm(List<String> footer) {
140 		if (footer.isEmpty()) {
141 			return 0;
142 		}
143 
144 		String s = footer.get(0);
145 		int p = s.indexOf(' ');
146 		if (p > 0) {
147 			s = s.substring(0, p);
148 		}
149 		return Long.parseLong(s, 10);
150 	}
151 
152 	private void blockUntil(ProposedTimestamp ts) throws IOException {
153 		try {
154 			ts.blockUntil(getSystem().getMaxWaitForMonotonicClock());
155 		} catch (InterruptedException | TimeoutException e) {
156 			throw new TimeIsUncertainException(e);
157 		}
158 	}
159 }