You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

TransportAmazonS3.java 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. /*
  2. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org>
  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. package org.eclipse.jgit.transport;
  44. import java.io.BufferedReader;
  45. import java.io.File;
  46. import java.io.FileNotFoundException;
  47. import java.io.IOException;
  48. import java.io.InputStream;
  49. import java.io.OutputStream;
  50. import java.net.URLConnection;
  51. import java.text.MessageFormat;
  52. import java.util.ArrayList;
  53. import java.util.Collection;
  54. import java.util.HashSet;
  55. import java.util.Map;
  56. import java.util.Properties;
  57. import java.util.TreeMap;
  58. import org.eclipse.jgit.JGitText;
  59. import org.eclipse.jgit.errors.NotSupportedException;
  60. import org.eclipse.jgit.errors.TransportException;
  61. import org.eclipse.jgit.lib.Constants;
  62. import org.eclipse.jgit.lib.ObjectId;
  63. import org.eclipse.jgit.lib.ObjectIdRef;
  64. import org.eclipse.jgit.lib.ProgressMonitor;
  65. import org.eclipse.jgit.lib.Ref;
  66. import org.eclipse.jgit.lib.Repository;
  67. import org.eclipse.jgit.lib.SymbolicRef;
  68. import org.eclipse.jgit.lib.Ref.Storage;
  69. /**
  70. * Transport over the non-Git aware Amazon S3 protocol.
  71. * <p>
  72. * This transport communicates with the Amazon S3 servers (a non-free commercial
  73. * hosting service that users must subscribe to). Some users may find transport
  74. * to and from S3 to be a useful backup service.
  75. * <p>
  76. * The transport does not require any specialized Git support on the remote
  77. * (server side) repository, as Amazon does not provide any such support.
  78. * Repository files are retrieved directly through the S3 API, which uses
  79. * extended HTTP/1.1 semantics. This make it possible to read or write Git data
  80. * from a remote repository that is stored on S3.
  81. * <p>
  82. * Unlike the HTTP variant (see {@link TransportHttp}) we rely upon being able
  83. * to list objects in a bucket, as the S3 API supports this function. By listing
  84. * the bucket contents we can avoid relying on <code>objects/info/packs</code>
  85. * or <code>info/refs</code> in the remote repository.
  86. * <p>
  87. * Concurrent pushing over this transport is not supported. Multiple concurrent
  88. * push operations may cause confusion in the repository state.
  89. *
  90. * @see WalkFetchConnection
  91. * @see WalkPushConnection
  92. */
  93. public class TransportAmazonS3 extends HttpTransport implements WalkTransport {
  94. static final String S3_SCHEME = "amazon-s3";
  95. static boolean canHandle(final URIish uri) {
  96. if (!uri.isRemote())
  97. return false;
  98. return S3_SCHEME.equals(uri.getScheme());
  99. }
  100. /** User information necessary to connect to S3. */
  101. private final AmazonS3 s3;
  102. /** Bucket the remote repository is stored in. */
  103. private final String bucket;
  104. /**
  105. * Key prefix which all objects related to the repository start with.
  106. * <p>
  107. * The prefix does not start with "/".
  108. * <p>
  109. * The prefix does not end with "/". The trailing slash is stripped during
  110. * the constructor if a trailing slash was supplied in the URIish.
  111. * <p>
  112. * All files within the remote repository start with
  113. * <code>keyPrefix + "/"</code>.
  114. */
  115. private final String keyPrefix;
  116. TransportAmazonS3(final Repository local, final URIish uri)
  117. throws NotSupportedException {
  118. super(local, uri);
  119. Properties props = null;
  120. File propsFile = new File(local.getDirectory(), uri.getUser());
  121. if (!propsFile.isFile())
  122. propsFile = new File(local.getFS().userHome(), uri.getUser());
  123. if (propsFile.isFile()) {
  124. try {
  125. props = AmazonS3.properties(propsFile);
  126. } catch (IOException e) {
  127. throw new NotSupportedException(MessageFormat.format(JGitText.get().cannotReadFile, propsFile), e);
  128. }
  129. } else {
  130. props = new Properties();
  131. props.setProperty("accesskey", uri.getUser());
  132. props.setProperty("secretkey", uri.getPass());
  133. }
  134. s3 = new AmazonS3(props);
  135. bucket = uri.getHost();
  136. String p = uri.getPath();
  137. if (p.startsWith("/"))
  138. p = p.substring(1);
  139. if (p.endsWith("/"))
  140. p = p.substring(0, p.length() - 1);
  141. keyPrefix = p;
  142. }
  143. @Override
  144. public FetchConnection openFetch() throws TransportException {
  145. final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects");
  146. final WalkFetchConnection r = new WalkFetchConnection(this, c);
  147. r.available(c.readAdvertisedRefs());
  148. return r;
  149. }
  150. @Override
  151. public PushConnection openPush() throws TransportException {
  152. final DatabaseS3 c = new DatabaseS3(bucket, keyPrefix + "/objects");
  153. final WalkPushConnection r = new WalkPushConnection(this, c);
  154. r.available(c.readAdvertisedRefs());
  155. return r;
  156. }
  157. @Override
  158. public void close() {
  159. // No explicit connections are maintained.
  160. }
  161. class DatabaseS3 extends WalkRemoteObjectDatabase {
  162. private final String bucketName;
  163. private final String objectsKey;
  164. DatabaseS3(final String b, final String o) {
  165. bucketName = b;
  166. objectsKey = o;
  167. }
  168. private String resolveKey(String subpath) {
  169. if (subpath.endsWith("/"))
  170. subpath = subpath.substring(0, subpath.length() - 1);
  171. String k = objectsKey;
  172. while (subpath.startsWith(ROOT_DIR)) {
  173. k = k.substring(0, k.lastIndexOf('/'));
  174. subpath = subpath.substring(3);
  175. }
  176. return k + "/" + subpath;
  177. }
  178. @Override
  179. URIish getURI() {
  180. URIish u = new URIish();
  181. u = u.setScheme(S3_SCHEME);
  182. u = u.setHost(bucketName);
  183. u = u.setPath("/" + objectsKey);
  184. return u;
  185. }
  186. @Override
  187. Collection<WalkRemoteObjectDatabase> getAlternates() throws IOException {
  188. try {
  189. return readAlternates(INFO_ALTERNATES);
  190. } catch (FileNotFoundException err) {
  191. // Fall through.
  192. }
  193. return null;
  194. }
  195. @Override
  196. WalkRemoteObjectDatabase openAlternate(final String location)
  197. throws IOException {
  198. return new DatabaseS3(bucketName, resolveKey(location));
  199. }
  200. @Override
  201. Collection<String> getPackNames() throws IOException {
  202. final HashSet<String> have = new HashSet<String>();
  203. have.addAll(s3.list(bucket, resolveKey("pack")));
  204. final Collection<String> packs = new ArrayList<String>();
  205. for (final String n : have) {
  206. if (!n.startsWith("pack-") || !n.endsWith(".pack"))
  207. continue;
  208. final String in = n.substring(0, n.length() - 5) + ".idx";
  209. if (have.contains(in))
  210. packs.add(n);
  211. }
  212. return packs;
  213. }
  214. @Override
  215. FileStream open(final String path) throws IOException {
  216. final URLConnection c = s3.get(bucket, resolveKey(path));
  217. final InputStream raw = c.getInputStream();
  218. final InputStream in = s3.decrypt(c);
  219. final int len = c.getContentLength();
  220. return new FileStream(in, raw == in ? len : -1);
  221. }
  222. @Override
  223. void deleteFile(final String path) throws IOException {
  224. s3.delete(bucket, resolveKey(path));
  225. }
  226. @Override
  227. OutputStream writeFile(final String path,
  228. final ProgressMonitor monitor, final String monitorTask)
  229. throws IOException {
  230. return s3.beginPut(bucket, resolveKey(path), monitor, monitorTask);
  231. }
  232. @Override
  233. void writeFile(final String path, final byte[] data) throws IOException {
  234. s3.put(bucket, resolveKey(path), data);
  235. }
  236. Map<String, Ref> readAdvertisedRefs() throws TransportException {
  237. final TreeMap<String, Ref> avail = new TreeMap<String, Ref>();
  238. readPackedRefs(avail);
  239. readLooseRefs(avail);
  240. readRef(avail, Constants.HEAD);
  241. return avail;
  242. }
  243. private void readLooseRefs(final TreeMap<String, Ref> avail)
  244. throws TransportException {
  245. try {
  246. for (final String n : s3.list(bucket, resolveKey(ROOT_DIR
  247. + "refs")))
  248. readRef(avail, "refs/" + n);
  249. } catch (IOException e) {
  250. throw new TransportException(getURI(), JGitText.get().cannotListRefs, e);
  251. }
  252. }
  253. private Ref readRef(final TreeMap<String, Ref> avail, final String rn)
  254. throws TransportException {
  255. final String s;
  256. String ref = ROOT_DIR + rn;
  257. try {
  258. final BufferedReader br = openReader(ref);
  259. try {
  260. s = br.readLine();
  261. } finally {
  262. br.close();
  263. }
  264. } catch (FileNotFoundException noRef) {
  265. return null;
  266. } catch (IOException err) {
  267. throw new TransportException(getURI(), MessageFormat.format(
  268. JGitText.get().transportExceptionReadRef, ref), err);
  269. }
  270. if (s == null)
  271. throw new TransportException(getURI(), MessageFormat.format(JGitText.get().transportExceptionEmptyRef, rn));
  272. if (s.startsWith("ref: ")) {
  273. final String target = s.substring("ref: ".length());
  274. Ref r = avail.get(target);
  275. if (r == null)
  276. r = readRef(avail, target);
  277. if (r == null)
  278. r = new ObjectIdRef.Unpeeled(Ref.Storage.NEW, target, null);
  279. r = new SymbolicRef(rn, r);
  280. avail.put(r.getName(), r);
  281. return r;
  282. }
  283. if (ObjectId.isId(s)) {
  284. final Ref r = new ObjectIdRef.Unpeeled(loose(avail.get(rn)),
  285. rn, ObjectId.fromString(s));
  286. avail.put(r.getName(), r);
  287. return r;
  288. }
  289. throw new TransportException(getURI(), MessageFormat.format(JGitText.get().transportExceptionBadRef, rn, s));
  290. }
  291. private Storage loose(final Ref r) {
  292. if (r != null && r.getStorage() == Storage.PACKED)
  293. return Storage.LOOSE_PACKED;
  294. return Storage.LOOSE;
  295. }
  296. @Override
  297. void close() {
  298. // We do not maintain persistent connections.
  299. }
  300. }
  301. }