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 12KB

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