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

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